结合表初始化和对象初始化 [英] Combining List initializer and object initializer
问题描述
时可以将一个列表初始化和对象初始化,同时结合? 考虑下面的类定义:
Is is possible to combine a List initializer and object initializer at the same time? Given the following class definition:
class MyList : List<int>
{
public string Text { get; set; }
}
// we can do this
var obj1 = new MyList() { Text="Hello" };
// we can also do that
var obj2 = new MyList() { 1, 2, 3 };
// but this one doesn't compile
//var obj3 = new MyList() { Text="Hello", 1, 2, 3 };
在设计这还是仅仅是一个错误或C#编译器的丢失的功能?
Is this by design or is it just a bug or missing feature of the c# compiler?
推荐答案
没有,望着定义从C#规范第7.6.10,一个对象或-集合初始化
EX pression是的或者的的对象初始化
的或的一个集合初始化
。
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
.
这是对象初始化
由多个的成员初始化
S,每个的形式为初始化=初始值
,而在集合初始化
由多个的元素的初始
S,每一个都是一个非assigment-EX pression
。
An object-initializer
is composed of multiple member-initializer
s, each of which is of the form initializer = initializer-value
whereas a collection-initializer
is composed of multiple element-initializer
s, each of which is a non-assigment-expression
.
因此,看起来是由设计 - 可能为简单起见。我不能说我所见过的希望的做到这一点,说实话。 (我通常不会从导出列表&LT; INT&GT;
来开始 - 我撰写它吧。)我真的很讨厌看到:
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<int>
to start with - I'd compose it instead.) I would really hate to see:
var obj3 = new MyList { 1, 2, Text = "Hello", 3, 4 };
编辑:如果你的真的,真的的要实现这一点,你可以在课堂上把这样的:
If you really, really want to enable this, you could put this in the class:
class MyList : List<int>
{
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 } };
这篇关于结合表初始化和对象初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!