如何在C#中将自动属性初始化为非空?

问题描述 投票:0回答:8

我有一处房产:

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

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

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

c# .net initialization automatic-properties
8个回答
7
投票

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

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

正如 nza他们的回答 中指出的那样,从 C# 6.0 开始,你可以这样做:

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

如果您使用此模式,那么每当您添加新属性时,您都会获得初始化属性,而无需在类的构造函数中添加初始化。


6
投票

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

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

4
投票

对于其他陷入这个老问题的人,C# 6.0 中有一个新功能。

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

public Dictionary<string, string> MyProp { get; set; } = 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 之外的任何内容都是只读的。


2
投票

在构造函数中初始化它

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

1
投票

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


1
投票

有一个名为 DefaultValueAttribute

属性类
,允许您指定所需的成员默认值,但是,它不会自动将成员设置为指定的值;不过,我们并没有失去希望,因为您可以使用反射在运行时检索该值并应用它,如互联网的这个角落中所示:

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);
    }
}

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


1
投票

如果您要运行此代码,您将收到 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>();
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.