Property initialization does not call set for List

前端 未结 2 1239
时光说笑
时光说笑 2021-01-17 04:12

I\'ve got a scenario I discovered when checking code coverage on a class\'s properties. When the property is of type List< T >, and an initializer is used, the set method

2条回答
  •  天命终不由人
    2021-01-17 04:38

    You could do either:

    public class ContainerClass
    {
        public string Text { get; set; }
        public List Items { get; set; }
    
        public ContainerClass()
        {
            Items = new List();
        }
    }
    

    Then:

    var arrange = new ContainerClass
    {
        Text = "SomeValue"
    };
    arrange.Items.Add(new Item(){Prop=Value});
    

    Or, if you don't use the constructor as stated, you can initialize a list like so:

    var arrange = new ContainerClass
    {
        Items = new List(){ new Item(){Prop=Value} }
    };
    

提交回复
热议问题