Anonymous types in C#
Def: When used with the new keyword, anonymous types can be created. An anonymous type is simply a nameless class that inherits from object. The definition of the class is inferred from the initializer, just as with implicitly typed variables.
Desc and Ex: If you need an object that contains a person’s first, middle, and last name, the declaration would look like this:
var captain = new {FirstName = "James", MiddleName = "T", LastName = "Kirk"};
This would produce an object with FirstName, MiddleName, and LastName properties. If you were to create another object that looked like this:
var doctor = new {FirstName = "Leonard", MiddleName = "", LastName = "McCoy"};
the types of captain and doctor are the same. You could set captain = doctor, for example.
If the values that are being set come from another object, then the initializer can be abbreviated. If you already have a class that contains the properties FirstName, MiddleName, and LastName and you have an instance of that class with the instance name person, then the captain object could be initialized like this:
var captain = new {person.FirstName, person.MiddleName, person.LastName};
The property names from the person object would be projected to the new object named captain. So the object named captain would have the FirstName, MiddleName, and LastName properties.
The actual type name of these new objects is unknown. The compiler “makes up” a name for the type, but only the compiler will ever be able to make use of it. So you can’t and shouldn’t plan on using any type reflection on the new objects because you will not get consistent results.
Дата добавления: 2015-09-18 | Просмотры: 624 | Нарушение авторских прав
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 |
|