Combining List initializer and object initializer

前端 未结 3 1099
难免孤独
难免孤独 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:17

    No, looking at the definitions from section 7.6.10 of the C# spec, an object-or-collection-initializer expression is either an object-initializer or a collection-initializer.

    An object-initializer is composed of multiple member-initializers, each of which is of the form initializer = initializer-value whereas a collection-initializer is composed of multiple element-initializers, each of which is a non-assigment-expression.

    So it looks like it's by design - possibly for the sake of simplicity. I can't say I've ever wanted to do this, to be honest. (I usually wouldn't derive from List to start with - I'd compose it instead.) I would really hate to see:

    var obj3 = new MyList { 1, 2, Text = "Hello", 3, 4 };
    

    EDIT: If you really, really want to enable this, you could put this in the class:

    class MyList : List
    {
        public string Text { get; set; }
        public MyList Values { get { return this; } }
    }
    

    at which point you could write:

    var obj3 = new MyList { Text = "Hello", Values = { 1, 2, 3, 4 } };
    

提交回复
热议问题