C # Serializes an object by field name

Source: Internet
Author: User

//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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.