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
字段可能具有不同的值。
5、static
如果 static 关键字应用于类,则类的所有成员都必须是静态的。不能通过实例引用静态成员。 然而,可以通过类型名称引用它。
public class MyBaseC
{
public struct MyStruct
{
public static int x = 100;
}
}
若要引用静态成员 x,除非可从相同范围访问该成员,否则请使用完全限定的名称 MyBaseC.MyStruct.x。