c# - 如何拥有 C# 只读功能但不限于构造函数?

标签 c# readonly lazy-initialization

C#“只读”关键字是一个修饰符,当字段声明包含它时,对声明引入的字段的赋值只能作为声明的一部分或在同一类的构造函数中出现。

现在假设我确实想要这个“一次赋值”约束,但我宁愿允许赋值在构造函数之外完成,可能是延迟/延迟评估/初始化。

我该怎么做?是否有可能以一种很好的方式做到这一点,例如,是否可以编写一些属性来描述它?

最佳答案

如果我没有正确理解您的问题,听起来您只想设置一次字段值(第一次),之后不允许再设置。如果是这样,那么之前所有关于使用 Lazy(及相关)的帖子可能会有用。但如果您不想使用这些建议,也许您可​​以这样做:

public class SetOnce<T> 
{
    private T mySetOnceField;
    private bool isSet;

    // used to determine if the value for 
    // this SetOnce object has already been set.
    public bool IsSet
    {
      get { return isSet; }
    }
    // return true if this is the initial set, 
    // return false if this is after the initial set.
    // alternatively, you could make it be a void method
    // which would throw an exception upon any invocation after the first.
    public bool SetValue(T value)
    {
       // or you can make thread-safe with a lock..
       if (IsSet)
       {
          return false; // or throw exception.
       }
       else 
       {
          mySetOnceField = value;
          return isSet = true;
       }
    }

    public T GetValue()
    {
      // returns default value of T if not set. 
      // Or, check if not IsSet, throw exception.
      return mySetOnceField;         
    }
} // end SetOnce

public class MyClass 
{
  private SetOnce<int> myReadonlyField = new SetOnce<int>();
  public void DoSomething(int number)
  {
     // say this is where u want to FIRST set ur 'field'...
     // u could check if it's been set before by it's return value (or catching the exception).
     if (myReadOnlyField.SetValue(number))
     {
         // we just now initialized it for the first time...
         // u could use the value: int myNumber = myReadOnlyField.GetValue();
     }
     else
     {
       // field has already been set before...
     }

  } // end DoSomething

} // end MyClass

关于c# - 如何拥有 C# 只读功能但不限于构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088491/

相关文章:

c# - 如何使用 System.Net.Mail 向电子邮件添加附件?

c# - 公共(public)静态只读字段与查找列表的 getter

c# - WCF - 无法获取元数据

c# - 通过 C# 中的方法强制添加到集合的模式

eclipse - 如何在Eclipse中使只读编辑器(Eclipse插件开发)

c# - 属性初始化和 'this'

java - Hibernate -> LazyInitializationException 与 n :m relation

android - API 19 上的惰性导致的应用程序崩溃

c# - 等效于 InsertonSubmit 的 Entity Framework

c# - 如何动态地将服务器控件添加到中继器中?