可以像以下示例中那样初始化实现IEnumerable和提供public void Add(/* args */)函数的类:
List<int> numbers = new List<int>{ 1, 2, 3 };
Run Code Online (Sandbox Code Playgroud)
Add(int)在初始化之后调用函数3x List<int>.
有没有办法明确地为我自己的类定义这种行为?例如,我可以让初始化程序调用除适当的Add()重载之外的函数吗?
是否可以同时组合List初始化器和对象初始化器?给定以下类定义:
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 };
Run Code Online (Sandbox Code Playgroud)
这是设计还是仅仅是c#编译器的错误或缺失功能?
我刚刚注意到在Visual Studio 2015中编写的C#中可以使用以下内容,但我以前从未见过它:
public class X
{
public int A { get; set; }
public Y B { get; set; }
}
public class Y
{
public int C {get; set; }
}
public void Foo()
{
var x = new X { A = 1, B = { C = 3 } };
}
Run Code Online (Sandbox Code Playgroud)
我的期望是Foo必须像这样实现:
public void Foo()
{
var x = new X { A = 1, B = new Y { C = 3 } };
} …Run Code Online (Sandbox Code Playgroud) 我有一个Manager有两个属性的类,如下所示:
public class Manager()
{
private string _name;
private List<int> _reportingEmployeesIds;
public string Name { get { return _name; }}
public List<int> ReportingEmployeesIds { get {return _reportingEmployeesIds; } }
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建Manager类的实例,如下所示
Manager m = new Manager
{
Name = "Dave", // error, expected
ReportingEmployeesIds = {2345, 432, 521} // no compile error - why?
};
Run Code Online (Sandbox Code Playgroud)
两个属性都缺少set属性,但编译器允许设置ReportingEmployeesIds,但不允许设置Name属性(错误:属性或索引器Manager.Name不能分配给它,它只是readonly).
为什么会这样?为什么编译器不会抱怨ReportingEmployeesIds只读.