C#中的概念理解

来源:互联网 发布:知乎怎样写文章 编辑:程序博客网 时间:2024/04/30 12:13
 
在C#中有很多和C语言,C++,Java相似之处,也有一些自己独有的特点,这些又是非常重要的地方,也是容易混淆的地方.主要有以下几点:
       1)变量声明
       C#中有8种基本数据类型,每种基本的数据类型都有默认值. 

C#数据类型
大小
默认值
示例
int
有符号的 32 位整数
0
int rating = 20;
float
32 位浮点数,精确到小数点后 7
0.0F
float temperature = 40.6F;
byte
无符号的 8 位整数
0
byte gpa = 2;
short
有符号的 16 位整数
0
short salary = 3400;
long
有符号的 64 位整数
0L
long population = 23451900;
bool
布尔值,true false
False
bool IsManager = true;
string
Unicode 字符串
-
string color = Orange
Char
单个 Unicode 字符
/0
char gender = M;
在声明类成员变量时,不赋值时也可以使用,该变量的值就是他的默认值,但如果声明的是方法成员变量,则在使用前必须初始化.如下例子所示:
class Class1
 {
//此变量自动初始化0,可以直接使用
  public int num; 
  public void Display()
  {
//此变量在使用前必须先显示初始化
      int n;  
     //如果是采用的下面这种方式声明的就会自动初始化为0
     //int n=new int(); 
  }
  }

2)const与readonly
const声明的属性成员,在声明时必须初始化,默认为static,属于类所有,不能用对象来访问,在运行过程中只读.是编译时常量.
readonly声明的属性成员,可以在声明是不初始化,但必须在构造时初始化,本类的每个对象都有一份,在运行时只读,是运行时常量.
如下例:
class Class1
 {
  public const int num1=100;  
  //public readonly int num2=200;
//在声明时可以不用初始化,但在构造时要进行初始化.
  public readonly int num2;  
  public Class1(int n)
  {
     num2=n;   
  }   
  [STAThread]
  static void Main(string[] args)
  {
   Class1 c=new Class1(300);
//只能通过类名来访问const字段
   Console.WriteLine("const num1={0}",Class1.num1); 
//通过对象名来访问readonly字段
   Console.WriteLine("readonly num2={0}",c.num2);   
  }
 }
原创粉丝点击