将值赋给返回永不为null的property

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

我有一个房产

public static List<int> intItems
{
    get { return _intItems ?? new List<int>(); }
    set { _intItems = value; }
}
private static List<int> _intItems;

这是可靠的永远不会。但是,当我对它进行Add值时,它不起作用。

intItems.Add(1);
Console.WriteLine(intItems.First()); //indexoutofrangeexception

为了使这项工作,我必须首先将值分配给私有字段以启用引用访问:

public static List<int> intItems
{
    get
    {
        if (_intItems == null)
        {
            _intItems = new List<int>();
        }
        return _intItems;
    }
    set { _intItems = value; }
}

我的问题是,有一个更优雅的方式,然后有12行代码的属性?我有这种类型的多种。

c# properties
2个回答
1
投票

作为canton7答案的替代方案,您可以在null上查看set

private static List<int> _intItems = new List<int>();

public static List<int> intItems {
  get { return _intItems; }
  set { _intItems = value ?? new List<int>(); }
}

1
投票

延迟加载属性的正常模式是:

private static List<int> _intItems;
public static List<int> IntItems
{
    get => _intItems ?? (_intItems = new List<int>());
    set => _intItems = value;
}

如果你的要求是阻止人们将属性设置为null,同时仍允许人们设置它,通常的方法是抛出异常:

private static List<int> _intItems = new List<int>();
public static List<int> IntItems
{
    get => _intItems;
    set => _intItems = value ?? throw new ArgumentNullException();
}

但是,如果您的要求只是您的属性永远不会返回null,那么为什么不这样做:

public static List<int> IntItems { get; } = new List<int>();
© www.soinside.com 2019 - 2024. All rights reserved.