C#语法解释

Ran*_*agg 1 .net c# syntax

我前几天看到这种语法,并想知道是否有人可以告诉我它是如何调用的,它是如何工作的以及它在哪里有用.

当我问它是如何工作的时候我的意思是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)

Tom*_*cek 9

它是调用对象初始化器集合初始化器,它允许您{ .. }在调用构造函数时在块中设置属性.在块中,您正在使用Setters = { ... }哪个是集合初始值设定项 - 它允许您指定集合的​​元素(这里,您不必创建集合的新实例 - 它只是添加花括号中的元素).有关详细信息,请参阅此MSDN页面.

通常,对象初始值设定项的语法有几个选项:

// Without explicitly mentioning parameter-less constructor:
new A { Prop1 = ..., Prop2 = ... }
// Specifying constructor arguments:
new A(...) { Prop1 = ..., Prop2 = ... }
Run Code Online (Sandbox Code Playgroud)

集合初始值设定项的语法如下所示:

// Creating new instance
new List<int> { 1, 2, 3 }
// Adding to existing instance inside object initializer:
SomeList = { 1, 2, 3 }
Run Code Online (Sandbox Code Playgroud)

值得一提的是,这与匿名类型密切相关(您不提供类型名称 - 编译器生成一些隐藏类型,您可以使用它var):

// Create anonymous type with some properties
new { Prop1 = ..., Prop2 = ... }
Run Code Online (Sandbox Code Playgroud)

所有这些功能都是C#3.0中的新功能.另请参阅此SO帖子,它解释了集合初始化程序的一些棘手方面(以您使用它们的样式).