是否可以在运行时分配 const 变量?c#.



我想要这种方法。

const public int x;

在运行时

x = 10; //this value will change it another Class  -->   (Not internal) 
x--> never change 

这有什么可能吗?

你不能在运行时为常量变量赋值,但你仍然可以在逻辑上达到你的要求,

可以创建静态只读属性和静态构造函数,并从静态构造函数赋值

public class ClassName
{
    static readonly int x;
    static ClassName()
    {
        x = 10;
    }
}

编译器在 const 属性和静态属性上的行为相同,内存分配也相同

所有常量声明都是隐式静态的

参考文献 https://blogs.msdn.microsoft.com/csharpfaq/2004/03/12/why-cant-i-use-static-and-const-together/

这使用const是不可能的。 const 应该在编译时初始化。

但是,还有另一种选择。您可以使用只读,您可以在运行时通过构造函数初始化它。

有关更多详细信息,请参阅https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants

https://www.safaribooksonline.com/library/view/c-cookbook/0596003390/ch03s25.html

不,你不能。

  • const 表示标记为 const 的成员的每个实例都将在编译期间替换为其值
  • 只读成员将在运行时解析。

最新更新