Combining List initializer and object initializer

前端 未结 3 1092
难免孤独
难免孤独 2020-12-18 20:35

Is is possible to combine a List initializer and object initializer at the same time? Given the following class definition:

class MyList : List
{
         


        
3条回答
  •  自闭症患者
    2020-12-18 21:09

    No, it's a not a bug. It is by design of the language.

    When you write

    var obj1 = new MyList() { Text="Hello" };
    

    this is effectively translated by the compiler to

    MyList temp = new MyList();
    temp.Text = "Hello";
    MyList obj = temp;
    

    When you write

    var obj2 = new MyList() { 1, 2, 3 };
    

    this is effectively translated by the compiler to

    MyList temp = new MyList();
    temp.Add(1);
    temp.Add(2);
    temp.Add(3);
    MyList obj2 = temp;
    

    Note that in the first case you are using an object initializer, but in the second case you are using a collection initializer. There is no such thing as an object-and-collection intializer. You are either initializing the properties of your object, or you are initializing the collection. You can not do both, this is by design.

    Also, you shouldn't derive from List. See: Inheriting List to implement collections a bad idea?

提交回复
热议问题