C#获取并设置List Collection的属性

Sha*_*arb 15 c#

Collection的属性如何设置?

我创建了一个带有Collection属性的类.我想在设置新值时随时添加到List中.在set方法中使用_name.Add(value)不起作用.

Section newSec = new Section();

newSec.subHead.Add("test string");
newSec.subHead.Add("another test string");

public class Section
{
    public String head { get; set; }
    private List<string> _subHead = new List<string>();
    private List<string> _content = new List<string>();

    public List<string> subHead
    {
        get
        { return _subHead; }
        set
        {
            _subHead.Add(value);
        }
    }
    public List<string> content
    {
        get
        { return _content; }
        set
        {
            _content.Add(value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用我的解决方案更新:

public class Section
{

    private List<string> _head = new List<string>();
    private List<string> _subHead = new List<string>();
    private List<string> _content = new List<string>();

    public List<string> Head
    {
        get
        { return _head; }
    }

    public List<string> SubHead
    {
        get
        { return _subHead; }
    }
    public List<string> Content
    {
        get
        { return _content; }
    }

    public void AddHeading(string line)
    {
        Head.Add(line);
    }

    public void AddSubHeading(string line)
    {
        SubHead.Add(line);
    }

    public void AddContent(string line)
    {
        Content.Add(line);
    }

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 25

将它作为setter的一部分是不合适的 - 它不像你真正设置整个字符串列表 - 你只是想添加一个.

有几个选择:

  • 在您的类中放置AddSubheadingAddContent方法,并且只显示列表的只读版本
  • 只使用getter公开可变列表,然后让调用者添加它们
  • 放弃封装的所有希望,只需使它们具有读/写属性

在第二种情况下,您的代码可以只是:

public class Section
{
    public String Head { get; set; }
    private readonly List<string> _subHead = new List<string>();
    private readonly List<string> _content = new List<string>();

    // Note: fix to case to conform with .NET naming conventions
    public IList<string> SubHead { get { return _subHead; } }
    public IList<string> Content { get { return _content; } }
}
Run Code Online (Sandbox Code Playgroud)

这是一个相当实用的代码,虽然它确实意味着调用者可以按照他们想要的方式改变你的集合,这可能并不理想.第一种方法保持最大的控制权(只有你的代码才能看到可变列表),但对于调用者来说可能不那么方便.

使集合类型的setter实际上只是将一个元素添加到现有集合既不可行也不愉快,所以我建议你放弃这个想法.