C# Syntax explanation
I saw a few days ago this syntax and wondered if someone could tell me how it is called, how does it work and where is it useful.
When I ask how does it work I mean that the Setters property is readonly(get), And the second is what do this braces mean: "Setters = {".
http://msdn.microsoft.com/en-us/library/ms601374.aspx
Thanks
datagrid.CellStyle = new Style(typeof(DataGridCell))
{
// Cancel the black border which appears when the user presses on a cell
Setters = { new Setter(Control.B开发者_StackOverflow社区orderThicknessProperty, new Thickness(0)) } // End of Setters
} // End of Style
It is call object initializer and collection initializer and it allows you to set properties in the { .. }
block when calling a constructor. Inside the block, you're using Setters = { ... }
which is a collection initializer - it allows you to specify elements of a collection (here, you don't have to create a new instance of the collection - it just adds elements in curly braces). For more information see this MSDN page.
In general, the syntax of object initializers has a few options:
// Without explicitly mentioning parameter-less constructor:
new A { Prop1 = ..., Prop2 = ... }
// Specifying constructor arguments:
new A(...) { Prop1 = ..., Prop2 = ... }
The syntax for collection initializers looks like this:
// Creating new instance
new List<int> { 1, 2, 3 }
// Adding to existing instance inside object initializer:
SomeList = { 1, 2, 3 }
It is worth mentioning that this is closely related to anonymous types (where you don't give a type name - the compiler generates some hidden type and you can work with it using var
):
// Create anonymous type with some properties
new { Prop1 = ..., Prop2 = ... }
All of these features are new in C# 3.0. See also this SO post which explains some tricky aspect of collection initializers (in the style you're using them).
instantiated the new object Style
, and than setting its property Setters
It's a c# 3.0 feature.
It seems to be setting default values when the object is being made. This is kind of like passing values to the constructor, but you aren't limited to just the options the constructor gives you.
精彩评论