【发布时间】:2014-07-30 14:53:28
【问题描述】:
我有一个本地字符串(文件路径),我只需要从函数中检索一次,我想确保它不再被修改。我不能使用const 关键字,因为我的字符串的值是在运行时而不是编译时确定的。所以我尝试改用 readonly 关键字,但 Visual Studio 告诉我它对我的项目无效。我怎样才能达到我想要的保护水平,最好不要再上课?
为了简单起见和公司政策,我(大幅)缩小并重命名了我的类和函数,但概念是相同的。
public class myClass
{
private void myFunction()
{
readonly string filePath = HelperClass.getFilePath("123");
//do stuff
}
}
public static class HelperClass
{
public static string getFilePath(string ID)
{
switch(ID)
{
case "123":
return "C:/123.txt";
case "234":
return "C:/234.txt";
default:
throw new Exception(ID + " is not supported");
}
}
}
=== 为 PS2Goat 编辑 ====
public class myClass
{
protected SomeObject o;
private virtual readonly string path;
public myClass(someObject o)
{
this.o = o;
path = HelperClass.getFilePath(o.getID());
}
private virtual void myFunction()
{
//do stuff
}
}
public class myDerivedClass
{
private override virtual readonly string path;
public myDerivedClass(someObject o) : base(o)
{
path = HelperClass.getFilePath(o.getID()); //ID will be different
}
private override void myFunction()
{
//do different stuff
}
}
public static class HelperClass
{
public static string getFilePath(string ID)
{
switch(ID)
{
case "123":
return "C:/123.txt";
case "234":
return "C:/234.txt";
default:
throw new Exception(ID + " is not supported");
}
}
}
看,所以我遇到的这个问题是,如果我想抛出异常,我现在必须在父类的构造函数中捕获它(直到支持该类),因为父构造函数将是在派生构造函数之前调用。因此,在调用子构造函数(具有正确 ID)之前,将设置一次错误的 ID。
【问题讨论】:
-
你不能在 getter/setter 中有一个带有逻辑的属性来防止或限制重新进入吗?
-
字符串是不可变的,因此如果您不将任何其他字符串实例分配给您的
filePath变量,那么它的值将不会改变。 -
我会考虑声明一个
readonly属性并在构造函数(或类型构造函数)中只初始化一次,但前提是getFilePath方法不需要花费大量时间 -
@Yuriy 是的,但我想让其他编码人员难以修改该值,它不应该在我的函数范围内进行修改。
-
除了标记的重复项,请参见stackoverflow.com/questions/2054761/…。
标签: c# .net string encapsulation protection