我正在查看C#集合初始化程序,发现实现非常务实,但也与C#中的任何其他内容完全不同
我能够创建这样的代码:
using System;
using System.Collections;
class Program
{
static void Main()
{
Test test = new Test { 1, 2, 3 };
}
}
class Test : IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(int i) { }
}
Run Code Online (Sandbox Code Playgroud)
由于我满足了编译器(已实现IEnumerable和a public void Add)的最低要求,因此无效,但显然没有价值.
我想知道是什么阻止了C#团队创建更严格的要求?换句话说,为了编译这种语法,为什么编译器不要求类型实现ICollection?这似乎更符合其他C#功能的精神.
有三种可能性,但我找不到例子:
我想写一些单元测试,看看我是否能处理他们,但我不知道怎么写他们除了第一个,这似乎是new Foo { Property = "value" }在那里属性="值"是类型的表达式MemberAssignment.
另请参阅此MSDN文章.
假设我有一个具有字典<string,bool>属性的类,使用对象初始化程序我可以使用这种语法(我觉得看起来很干净):
new MyClass()
{
Table = { {"test",true},{"test",false} }
}
Run Code Online (Sandbox Code Playgroud)
但是,在初始化程序之外我不能这样做:
this.Table = { {"test",true},{"test",false} };
Run Code Online (Sandbox Code Playgroud)
为什么初始化器是特例?我猜测它与LINQ要求,协方差或诸如此类的东西有关,但感觉有点不一致,无法在任何地方使用这种初始化器...
考虑以下两个程序.第一个程序在编译时因编译器错误而失败:
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
List<int> bar = { 0, 1, 2, 3 }; //CS0622
}
}
Run Code Online (Sandbox Code Playgroud)
只能使用数组初始值设定项表达式分配给数组类型.请尝试使用新表达式.
这个我完全明白. 当然,解决方法是使用new[] {...}数组初始化程序语法,程序将编译并正确运行.
现在考虑第二个程序,只是略有不同:
using System.Collections.Generic;
public class Foo {
public IList<int> Bar { get; set; }
}
class Program {
static void Main(string[] args) {
Foo f = new Foo { Bar = { 0, 1, 2, 3 } }; //Fails at run time
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序编译.而且,生成的运行时错误是:
你调用的对象是空的.
这对我很有意思.为什么第二个程序甚至会编译?我甚至尝试制作Bar一个实例变量而不是属性,认为这可能与奇怪的行为有关.它不是.与第一个示例一样,使用new[] {...} …
我前几天看到这种语法,并想知道是否有人可以告诉我它是如何调用的,它是如何工作的以及它在哪里有用.
当我问它是如何工作的时候我的意思是Setters属性是readonly(get),第二个是这个括号的含义:"Setters = {".
http://msdn.microsoft.com/en-us/library/ms601374.aspx
谢谢
datagrid.CellStyle = new Style(typeof(DataGridCell))
{
// Cancel the black border which appears when the user presses on a cell
Setters = { new Setter(Control.BorderThicknessProperty, new Thickness(0)) } // End of Setters
} // End of Style
Run Code Online (Sandbox Code Playgroud)