Recommendation 19: Class with more efficient objects and collections.
Depending on the syntax rules after the attribute and FCL 3.5, we now have a cleaner and more efficient object and set initialization mechanism: object and collection initialization settings.
Object initialization:
classPerson { Public stringName {Get;Set; } Public intAge {Get;Set; } } classProgram {Static voidMain (string[] args) { person person=NewPerson () {Name ="Mike", age = -}; Console.read (); } }
Object initialization settings support the assignment of auto-implemented properties in curly braces. In the past, you can only rely on the construction method to pass the value in, or after the object is constructed, the property is assigned value. Now that the steps are simplified, the initialization setting is actually equivalent to the compiler assigning the property after the object has been generated.
The same simplification of the collection initialization:
list<person> personlist=New list<person>() { new] Rose", age=, person , null };
Using the collection initialization setting, the compiler calls the Add method on the collection after the collection object has been created.
The above code demonstrates how to create a new object or an existing object in an initialization statement, as well as a null value.
However, initializing the settings is not only convenient for object and collection initialization, the properties of the anonymous type in the collection returned by the LINQ query are read-only, and if you need to assign a value to an anonymous Type property, or add an attribute, you can only do so by initializing the setting. Initialization settings can also use expressions for properties.
The following code creates a new anonymous type in the LINQ query that contains the property name and Agescope, and agescope needs to be obtained by calculating the age property of the person.
List<person> PersonList2 =NewList<person>() { NewPerson () {Name ="Rose", age = + }, NewPerson () {Name ="Steve", age = $ }, NewPerson () {Name ="Jessica", age = - }, }; varPtemp = fromPinchPersonList2Select New{p.name, agescope = p.age > -?" Old":" Young" }; foreach(varIteminchptemp) {Console.WriteLine (string. Format ("{0}:{1}", item. Name, item. Agescope)); }
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 19: Class with more efficient objects and collections.