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

发布于 2024-10-31 13:58:24 字数 197 浏览 4 评论 0原文

我有一个属性:

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

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

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

I have a property:

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

When I invoke that property to add an item, I get a NullReferenceException.

How would I do the null check in the property itself so it gives me a new one if it is null? While keeping in the auto-property pattern.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

微凉徒眸意 2024-11-07 13:58:24

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

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

正如 nza 指出的在他们的答案中,从 C# 6.0 开始,您可以执行以下操作:

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

如果您使用此模式,那么每当您添加新的,无需在类的构造函数中添加初始化。

Without an explicit private variable the only other way would be to add some code to the constructor of the class:

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

As nza points out in their answer from C# 6.0 onwards you can do this:

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

If you use this pattern then you'll get initialised properties whenever you add a new one, without having to add the initialisation in the class's constructor.

何必那么矫情 2024-11-07 13:58:24

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

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

You can initialize it in your constructor:

public MyClass()
{
  MyProp = new Dictionary<string, string>();
}
童话里做英雄 2024-11-07 13:58:24

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

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

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

For other people falling over this old question, there is a new feature in C# 6.0.

In C# 6.0, you can also initialize that property to some constant value in the same statement, like this:

public Dictionary<string, string> MyProp { get; set; } = new Dictionary<string, string>();
慢慢从新开始 2024-11-07 13:58:24

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

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

这里您使用内部设置器来创建字典。之后,如果您想向字典中添加元素,您可以在代码中执行此操作:

InstanceOfMyClass.MyProp.Add(blah, blah);

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

I don't think you will want a setter, since that will always make a new dictionary, as others have pointed out by calling the setter in the constructor. A better approach is:

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

Here you've used the internal setter to create the dictionary. After this, if you want to add an element to the dictionary, you would do this in your code:

InstanceOfMyClass.MyProp.Add(blah, blah);

where you use the getter to get the dictionary object, then do an Add to add a new item. You can't call the setter from your code and accidentally wipe out the dictionary, because it will look readonly to anything outside of MyClass.

千寻… 2024-11-07 13:58:24

在构造函数中初始化它

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

Initialize it in the constructor

public MyClass(){  dictionary = new
 Dictionary<string,string>() 
}
ζ澈沫 2024-11-07 13:58:24

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

You will have to use an explicit backing field, you cannot change the getter or setter for auto-properties.

好久不见√ 2024-11-07 13:58:24

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

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

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

There's an attribute class named DefaultValueAttribute that allows you to specify the desired default value of a member, however, it doesn't automatically set the member to the value specified; hope is not lost, though, as you can use reflection to retrieve this value at runtime and apply it, as posed in 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);
    }
}

I haven't tested this, and there may be issues with certain types but I'll leave it to your consideration and discretion. Should you decide to implement this then improvements could certainly be made.

落花浅忆 2024-11-07 13:58:24

如果您要运行此代码,您将收到 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>();
        }
    }
}

If you were to run this code, you would get a NullReferenceException because the field is never initialized.

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

So one way to solve this would be to initialize it, in the class´s constructor.

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>();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文