//C # provides generics like templates in C + +, here is an example, combined with generics and reflection, lets us find variable members in a class by string and assign values. This is useful, for example, when we read data from a database or an XML file, we can assign values by field names to automate serialization/*The String.Format method replaces each format item in the specified string with the text equivalent of the value of the corresponding object*/usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceconsoleapplication7{classProgram {Static voidMain (string[] args) { //Create a Player objectPlayer p =NewPlayer (); //to copy a Player object by field nameSetobjectvalue<player> (P,"name","Goodman"); Setobjectvalue<Player> (P,"ID", -); Console.WriteLine (string. Format ("Name:{0},id:{1}", p.name,p.id)); Console.ReadLine (); } //a player class that includes a name and an ID of two members Public classPlayer { Public stringName =string. Empty; Public intID =0; } //a function that uses generics,<t> is a generic parameter, which can be any type of object ' Public Static voidSetobjectvalue<t> (T obj,stringFieldNameObjectvalue) { //get the member variable of an object by field nameSystem.Reflection.FieldInfo info =obj. GetType (). GetField (fieldname); if(Info! =NULL) { //Assigning a value to a member variableinfo. SetValue (Obj,value); } } }}
C # Serializes an object by field name