C# 中静态、只读和常量之间的区别
本文关键字:常量 之间 区别 只读 静态 | 更新日期: 2023-09-19 21:44:09
下表列出了 C# 中 Static 、只读和常量之间的区别。
static | readonly | const |
---|---|---|
使用 static 关键字声明。 | Declared using the readonly keyword. | Declred using the const keyword.
By default a const is static that cannot be changed. |
类、构造函数、方法、变量、属性、事件和运算符可以是静态的。 结构、索引器、枚举、析构函数或终结器不能是静态的。 | Only the class level fields can be readonly. The local variables of methods cannot be readonly. | Only the class level fields or variables can be constant. |
只能在静态方法中访问静态成员。非静态方法无法访问静态成员。 | Readonly fields can be initialized at declaration or in the constructor. Therefore, readonly variables are used for the run-time constants. | The constant fields must be initialized at the time of declaration. Therefore, const variables are used for compile-time constants. |
可以使用 ClassName.StaticMemberName 修改静态成员的值。 | Readonly variable cannot be modified at run-time. It can only be initialized or changed in the constructor. | Constant variables cannot be modified after declaration. |
静态成员可以使用 ClassName.StaticMemberName 访问,但不能使用 object 访问。 | Readonly members can be accessed using object, but not ClassName.ReadOnlyVariableName . | Const members can be accessed using ClassName.ConstVariableName , but cannot be accessed using object. |
下面的示例演示静态、只读和常量变量之间的区别。
示例: static vs readonly vs const
public class Program
{
public static void Main()
{
MyClass mc = new MyClass(50);
mc.ChangeVal(45);
mc.Display();
Console.WriteLine("MyClass.constvar = {0}", MyClass.constvar);
Console.WriteLine("MyClass.staticvar = {0}", MyClass.staticvar);
}
}
public class MyClass
{
public readonly int readonlyvar1 = 10, readonlyvar2;
public const int constvar = 20;
public static int staticvar = 0;
public MyClass(int i)
{
readonlyvar2 = i; // valid
//z = i; //compile-time error
staticvar = i; // valid
}
public void ChangeVal(int val)
{
//x = val;
//z = i; //compile-time error
staticvar = val; // valid
}
public void Display()
{
Console.WriteLine(staticvar);
Console.WriteLine(readonlyvar1);
Console.WriteLine(constvar);
}
}