c# - 制作只读本地字符串 C#

标签 c# .net string encapsulation protection

我有一个本地字符串(文件路径),我只需要从一个函数中检索一次,并且我想确保它再也不会被修改。我不能使用 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。

最佳答案

您不能在一个方法中限定只读变量的范围。因此它应该被提升为 readonly static领域:

public class myClass
{
    private readonly static string filePath = HelperClass.getFilePath("123");
    private void myFunction()
    {    
      //do stuff
    }
}

这将导致您的 filePath访问 myClass 时要初始化的变量首次。如果这不是您想要的,getFilePath是一个长时间运行/昂贵的操作,你想等到 myFunction被调用,您可以将实现替换为 System.Lazy<T> :

public class myClass
{
    private readonly static Lazy<string> filePath 
            = new Lazy<string>(() => HelperClass.getFilePath("123")));
    private void myFunction()
    {   
      string path = filePath.Value;
      //do stuff
    }
}

关于c# - 制作只读本地字符串 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25040040/

相关文章:

c# - 我需要一个网络应用程序中的通知系统

c# - 如何清除 ElementHost 控件的内存泄漏

.net - 在 .net 中创建对列表

.net - 以编程方式获取 Web 服务的参数?

R:如何通过仅比较每个字符串中的前 3 个制表符分隔项来对两个字符串向量使用 setdiff?

c# - mscorlib.dll 中发生奇怪的错误 'System.ExecutionEngineException'

c# MVC 有条件地隐藏标题按钮

c# - 如何使事件回调进入我的 win 表单线程安全?

python - 从python中的列表中删除重复的字符串

c++ - 添加字符串和文字 (C++)