可以在运行时分配一个const变量吗?C#

Mr.*_*eel 2 c#

我想要这种方法.

const public int x;
Run Code Online (Sandbox Code Playgroud)

在运行时

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

x--> never change 
Run Code Online (Sandbox Code Playgroud)

有可能吗?

pro*_*res 10

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

您可以创建静态只读属性和静态构造函数,并从静态构造函数中指定值

public class ClassName
{
    static readonly int x;

    static ClassName()
    {
        x = 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器对const属性和静态属性的作用相同,内存分配也相同

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

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