将变量转换为常量

Jul*_*n50 4 c# variables constants

Can 似乎很奇怪,但是有没有办法将变量声明或转换为常量,例如:

string myVariable = "MyString";
const string myConstant = myVariable ;
Run Code Online (Sandbox Code Playgroud)

我需要这个来回答我的问题: linq to sql startwith performance indexed columns

谢谢

BRA*_*mel 6

不,没有办法做到这一点,因为Const Const 值在编译时直接烧录到调用站点中,相反,您可以readonly在构造函数中创建并分配它

就像是

string myVariable = "MyString";
readonly  string myConstant="test" ; 
public MyClass()
{ 
myConstant= myVariable ;
}
Run Code Online (Sandbox Code Playgroud)