这是我的类(class):
namespace My.Core
{
public static class Constants
{
public const string Layer_ver_const = "23";
public const string apiHash_const = "111111";
}
}
现在我想为 apiHash_const 设置条件值。
意思是:
if(Layer_ver_const == "23")
{
apiHash_const = "111111";
}
else if(Layer_ver_const == "50")
{
apiHash_const = "222222";
}
else
{
apiHash_const = "333333";
}
我该怎么做?
最佳答案
恐怕你不能在运行时这样做。但是您始终可以将常量关键字更改为 static
或 static readonly
,此代码将起作用。
public static class Constants
{
public const string Layer_ver_const = "23";
public static readonly string apiHash_const;
static Constants()
{
if(Layer_ver_const == "23")
{
apiHash_const = "111111";
}
else if(Layer_ver_const == "50")
{
apiHash_const = "222222";
}
else
{
apiHash_const = "333333";
}
}
}
如果您想知道 constant
和 static readonly
之间的区别,请查看此链接:
关于c# - 将条件值分配给静态类的类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37366249/