Psy*_*ula -3 c# class constants
我想在我的班级中声明一个变量,以后不能像这样更改:
obj myobj=new obj()
myobj.CONSTANT_VAR="Changed value" //ERROR!!
Run Code Online (Sandbox Code Playgroud)
...但其值可以像这样访问:
Console.WriteLine(myobj.CONSTANT_VAR)
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
public class obj{
public int a, b;
public const string CONSTANT_VAR;
public obj(int x,int y){
a=x;
b=y;
CONSTANT_VAR=1/(a*((""+a).Length)+3/(b*((""+b).Length)).ToString();
}
public int do(){
return this.a+this.b-(CONSTANT_VAR).Length;
}
}
class DriverClass(){
static void Main(){
obj myObj=new obj(2,3);
myObj.a=34;
myObj.b=35;
myObj.CONSTANT_VAR="changed ur string lol"; //i want it to print error
Console.WriteLine(CONSTANT_VAR); //no error
Console.WriteLine(myObj.add());
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误消息:
constants must have a value assigned
Run Code Online (Sandbox Code Playgroud)
但我不想事先给它赋值..... 我该怎么办?
您正在寻找只读字段或属性,而不是 const真正的全局常量。
我建议完全避免使用公共字段,而是使用属性 - 因此在这种情况下,您需要一个仅获取属性。遵循 .NET 命名约定,您将获得以下内容:
public class Obj
{
public int A { get; set; }
public int B { get; set; }
public string ConstantVar { get; }
public Obj(int x, int y)
{
A = x;
B = y;
ConstantVar = /* complex expression */
}
public int Do() => A + B - ConstantVar.Length;
}
Run Code Online (Sandbox Code Playgroud)