gpt4 book ai didi

.net - 具有自动属性的集合初始值设定项

转载 作者:行者123 更新时间:2023-12-01 11:57:19 25 4
gpt4 key购买 nike

有没有办法在使用自动属性的同时使用集合初始值设定项?

// Uses collection initializer but not automatic properties
private List<int> _numbers = new List<int>();
public List<int> Numbers
{
get { return _numbers; }
set { _numbers = value; }
}


// Uses automatic properties but not collection initializer
public List<int> Numbers { get; set; }


// Is there some way to do something like this??
public List<int> Numbers { get; set; } = new List<int>();

最佳答案

不,基本上。您必须在构造函数中初始化集合。老实说,无论如何,可设置的集合很少是个好主意;;我实际上只使用(更改您的第一个版本,删除 set):

private readonly List<int> _numbers = new List<int>();
public List<int> Numbers { get { return _numbers; } }

或者如果我想将构造推迟到第一次访问时:

private List<int> _numbers;
public List<int> Numbers {
get { return _numbers ?? (_numbers = new List<int>()); }
}

关于.net - 具有自动属性的集合初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5749239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com