C# 基础之const

1、使用 const 关键字来声明某个常量字段或常量局部变量。常量字段和常量局部变量不是变量并且不能修改。 常量可以为数字、布尔值、字符串或 null 引用(Constants can be numbers, Boolean values, strings, or a null reference)。

下面代码会报编译错误:

public const DateTime myDateTime = new DateTime(2018,05,23,0,0,0);

2、不允许在常数声明中使用 static 修饰符。

  static const string a = "a";  //Error

报错:不能将变量“a”标记为static。

3、常数可以参与常数表达式,如下所示:

public const int c1 = 5;  
public const int c2 = c1 + 100;

4、readonly 关键字与 const 关键字不同:const 字段只能在该字段的声明中初始化。readonly字段可以在声明或构造函数中初始化。因此,根据所使用的构造函数,`readonly` 字段可能具有不同的值。

 1  class ReadOnly
 2     {
 3         private readonly string str;
 4         public ReadOnly()
 5         {
 6             str = @"ReadOnly() 构造函数";
 7             Console.WriteLine(str);
 8         }
 9         public ReadOnly(int i)
10             : this()
11         {
12             str = @"ReadOnly(int i) 构造函数";
13             Console.WriteLine(str);
14             str = @"asd";
15             Console.WriteLine(str);
16         }
17      }
ReadOnly 构造函数初始化字符串

调用:     ReadOnly ro = new ReadOnly(1);

输出:

猜你喜欢

转载自www.cnblogs.com/meng9527/p/9078525.html