C# object initialization of read only collection properties

后端 未结 4 1572
南笙
南笙 2020-11-27 21:11

For the life of me, I cannot figure out what is going on in the example piece of C# code below. The collection (List) property of the test class is set as read only, but ye

相关标签:
4条回答
  • 2020-11-27 21:39

    This:

    MyClass c = new MyClass
    {
        StringCollection = { "test2", "test3" }
    };
    

    is translated into this:

    MyClass tmp = new MyClass();
    tmp.StringCollection.Add("test2");
    tmp.StringCollection.Add("test3");
    MyClass c = tmp;
    

    It's never trying to call a setter - it's just calling Add on the results of calling the getter. Note that it's also not clearing the original collection either.

    This is described in more detail in section 7.6.10.3 of the C# 4 spec.

    EDIT: Just as a point of interest, I was slightly surprised that it calls the getter twice. I expected it to call the getter once, and then call Add twice... the spec includes an example which demonstrates that.

    0 讨论(0)
  • 2020-11-27 21:39

    You aren't calling the setter; you are essentially calling c.StringCollection.Add(...) each time (for "test2" and "test3") - it is a collection initializer. For it to be the property assignment, it would be:

    // this WON'T work, as we can't assign to the property (no setter)
    MyClass c = new MyClass
    {
        StringCollection = new StringCollection { "test2", "test3" }
    };
    
    0 讨论(0)
  • 2020-11-27 21:40

    The StringCollection property doesn't have a setter so unless you add one you cannot modify its value.

    0 讨论(0)
  • 2020-11-27 21:49

    I think that, beeing read only, you can't do

    c.StringCollection = new List<string>();
    

    But you can assign items to list...
    Am I wrong?

    0 讨论(0)
提交回复
热议问题