【问题标题】:How to initialize auto-property to not null in C#?如何在 C# 中将自动属性初始化为不为空?
【发布时间】:2011-04-10 17:02:54
【问题描述】:

我有一个财产:

public Dictionary<string, string> MyProp { get; set; }

当我调用该属性来添加项目时,我得到一个 NullReferenceException。

我将如何对属性本身进行 null 检查,以便在它为 null 时给我一个新的?同时保持自动属性模式。

【问题讨论】:

    标签: c# .net initialization automatic-properties


    【解决方案1】:

    如果没有显式的私有变量,唯一的另一种方法是向类的构造函数添加一些代码:

    MyProp = new Dictionary<string,string>();
    

    【讨论】:

    • 好吧,我用了这个,它是最干净的。
    【解决方案2】:

    你可以在你的构造函数中初始化它:

    public MyClass()
    {
      MyProp = new Dictionary<string, string>();
    }
    

    【讨论】:

      【解决方案3】:

      我不认为你会想要一个 setter,因为这总是会产生一个新的字典,正如其他人通过在构造函数中调用 setter 所指出的那样。更好的方法是:

      public Dictionary<string, string> MyProp { get; internal set; }
      public MyClass() { MyProp = new Dictionary<string, string>(); }
      

      在这里,您使用了内部设置器来创建字典。在此之后,如果你想向字典中添加一个元素,你可以在你的代码中这样做:

      InstanceOfMyClass.MyProp.Add(blah, blah);
      

      您使用 getter 获取字典对象,然后执行 Add 以添加新项目。您不能从代码中调用 setter 并意外清除字典,因为它对 MyClass 之外的任何内容都是只读的。

      【讨论】:

      • 出于兴趣,为什么是内部而不是私人?
      • 好点 - 这取决于用例。 internal 将授予同一程序集中的任何其他类对 setter 的访问权限。私人可能更有意义。
      【解决方案4】:

      对于遇到这个老问题的其他人来说,C# 6.0 中有一个新功能。

      在 C# 6.0 中,您还可以在同一语句中将该属性初始化为某个常量值,如下所示:

      public Dictionary<string, string> MyProp { get; set; } = new Dictionary<string, string>();
      

      【讨论】:

      • 我会删除 setter,因为您可能不想重新创建字典对象。仅声明 getter 是有效的。
      【解决方案5】:

      在构造函数中初始化

      public MyClass(){  dictionary = new
       Dictionary<string,string>() 
      }
      

      【讨论】:

        【解决方案6】:

        您必须使用显式支持字段,您不能更改自动属性的 getter 或 setter。

        【讨论】:

          【解决方案7】:

          有一个名为DefaultValueAttributeattribute class 允许您指定所需的成员默认值,但是它不会自动将成员设置为指定的值;但是,希望不会丢失,因为您可以使用反射在运行时检索此值并应用它,如 this corner of the internet 中所述:

          static public void ApplyDefaultValues(object self)
          {
              foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(self))
              {
                  DefaultValueAttribute attr = prop.Attributes[typeof(DefaultValueAttribute)] as DefaultValueAttribute;
                  if (attr == null) continue;
                  prop.SetValue(self, attr.Value);
              }
          }
          

          我没有对此进行测试,某些类型可能存在问题,但我会留给您考虑和判断。如果您决定实施这一点,那么肯定可以进行改进。

          【讨论】:

          • 这看起来非常老套和复杂。
          • 好吧,我不能适当地提倡它;但它一种可能性。
          【解决方案8】:

          如果您要运行此代码,您将收到 NullReferenceException,因为该字段从未初始化。

          class Program
          {
              static void Main(string[] args)
              {
                  Person sergio = new Person();
                  sergio.Items.Add("test", "test");
          
                  Console.ReadKey();
              }
          
              public class Person
              {
                  public Dictionary<string, string> Items { get; set; }
              }
          }
          

          所以解决这个问题的一种方法是在类的构造函数中初始化它。

          class Program
          {
              static void Main(string[] args)
              {
                  Person sergio = new Person();
                  sergio.Items.Add("test", "test");
          
                  Console.ReadKey();
              }
          
              public class Person
              {
                  public Dictionary<string, string> Items { get; set; }
          
                  public Person()
                  {
                      Items = new Dictionary<string, string>();
                  }
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2014-04-03
            • 2011-02-04
            • 1970-01-01
            • 1970-01-01
            • 2020-08-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-30
            相关资源
            最近更新 更多