现在的位置: 首页 > 综合 > 正文

C#基本语法知识

2013年02月09日 ⁄ 综合 ⁄ 共 2482字 ⁄ 字号 评论关闭

第一个程序,采用MessageBox.Show显示小对话框:

   1: /*

   2:  * Created by SharpDevelop.

   3:  * User: feisky

   4:  * Date: 2009-10-27

   5:  * Time: 10:46

   6:  * 

   7:  * To change this template use Tools | Options | Coding | Edit Standard Headers.

   8:  */

   9: using System;

  10: using System.Collections.Generic;

  11: using System.Drawing;

  12: using System.Windows.Forms;

  13:  

  14: namespace test

  15: {

  16:     /// <summary>

  17:     /// Description of MainForm.

  18:     /// </summary>

  19:     public partial class MainForm : Form

  20:     {

  21:         public MainForm()

  22:         {

  23:             //

  24:             // The InitializeComponent() call is required for Windows Forms designer support.

  25:             //

  26:             InitializeComponent();

  27:             

  28:             //

  29:             // TODO: Add constructor code after the InitializeComponent() call.

  30:             //

  31:         }

  32:         

  33:         void BtnShowDlgClick(object sender, EventArgs e)

  34:         {

  35:             MessageBox.Show("The first Csharp app.");

  36:         }

  37:     }

  38: }

1.基本语法

  • 区分大小写
  • 注释:/* */     //         ///
  • 简单类型变量:sbyte byte short ushort int unit long ulong float double decimal char(Unicode) bool (前面的都是值类型),string(引用类型)
  • 控制台输出变量的格式:Console.WriteLine("{0}+{1}={2}",x,y,z);
  • 类型转换:Convert.ToDouble()  (int)x
  • 运算符:+ – * / % 及复合赋值运算 逻辑运算 位运算 (x<10)?x=10:x=0 
  • 命名空间的使用
  • 流程控制:if..else  if…else if…else   switch…case while for  do…while   break continue
  • enum struct
  • 数组:int[] a=new int[5]; int[] a={1,2,2,2,2};  double[,] test=new double[3,4];  int[][] test;数组的数组  foreach(int i in Array)       //循环访问数组 这是一种只读访问

2.字符串处理

3.函数

  • 定义:static double getVal() {}
  • 参数:参数匹配 参数数组 params <type>[] <name>
  • 引用参数:get(ref int val) val必须已经初始化   在调用的时候也必须加上ref关键字
  • 输出参数:out 此参数不需要初始化 在调用的时候也必须加上out关键字
  • 结构函数:结构体中可以定义public函数
  • 重载:创建同名多个函数,但参数要求不同
  • 委托:把引用存储为函数的类型,主要用在事件的处理中
  • 错误处理:try..catch..finally

4.类的基本知识

  • 抽象类:sbstarct,不能实例化、只能继承,可有抽象成员,主要用作类的基类
  • 密封类:sealed,不能继承的类
  • 继承:只允许有一个基类,且基类只能紧跟在冒号之后
  • internal类:只能在当前工程访问
  • public类:可在任何地方访问
  • 接口interface:不能使用abstarct和sealed,不能包含字段、构造析构函数、静态成员或常量,其成员是公共的,不能包含代码提
  • 构造函数执行序列:System.Object构造函数->基类构造函数->该类的构造函数 其中,可以通过base指定基类的非默认构造函数,使用this来指定本类非默认构造函数

5.类的成员

  • public private类内访问 internal工程内访问 protected类或派生类访问 static静态成员
  • 字段:可以用readonly表示只读 也可以用const定义常量
  • 方法:static类的方法 virtual可以重写 abstract必须重写 override重写了一个基类方法 extern定义在其他地方
  • 属性:set get控制
  • base基类  this当前对象实例
【上篇】
【下篇】

抱歉!评论已关闭.