C # Basic Series-Reflection notes

Source: Internet
Author: User

The use of reflection also has a few years, but has always felt that the concept of anti-abstract, today there is time to summarize this knowledge point.

1, why need reflection:

When you first use reflection, as a side dish you always don't understand, since you can get the object by new object, and then call the property and method through the object, then why do you need reflection to call it? Later used to find that this is a binding or post-binding problems, many early use of reflection developers often have similar doubts: since the development of the code can be written, why still put in the run time to do, not only cumbersome, and efficiency is also affected. Bloggers feel that the main problem is applicability, if your system does not have that high scalability and flexibility requirements, you can not consider reflection. But in architectural design, many things need to consider reusability, and in certain scenarios you do not have a specific class, you have to use the reflection. Bloggers summed up their own use of the reflection scene:

(1) Sometimes do not know the specific type, you can go through the DLL to get the object of the class;

(2) Some special methods, transmitted by the generic class, need to deal with some special business by reflection;

(3) The common method for the conversion of the DataTable and list<t> need to use reflection;

2. How to use reflection:

(1) A reflection DLL gets a class member:

There is a person class in an unknown DLL.

     Public classPerson {Private stringaddress; Private stringemail;  Public stringName {Set;Get; }  Public intAge {Set;Get; }  Public voidSayHello () {Console.WriteLine ("Hello"); }         Public Static stringMystaticpro {Set;Get; }  Public Static voidmystatic () {Console.WriteLine ("I'm the static method ."); }    }

Get the person class by reflection DLL

        Static voidMain (string[] args) {            //Reflection DLLs            varStrdllpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Dll\\reflectordll.dll"); varoassembly =Assembly.loadfile (Strdllpath); varLsttypes =oassembly.gettypes (); foreach(varOtypeinchlsttypes) {                if(Otype.name = =" Person")                {                    //all public members below the class are given by default                    varLstmembers =otype.getmembers (); foreach(varOmeminchlstmembers) {Console.WriteLine ("the GetMembers () method gets the name of the member:"+omem.name); } Console.WriteLine (""); //all public properties below the class are obtained by default                    varLstproperty =otype.getproperties (); foreach(varOpropinchLstproperty) {Console.WriteLine ("the GetProperties () method gets the name of the member:"+oprop.name); } Console.WriteLine (""); //all public fields below the class are given by default                    varLstfield =Otype.getfields (); foreach(varOfieldinchLstfield) {Console.WriteLine ("the GetFields () method gets the name of the member:"+ofield.name);        }}} Console.readkey (); }

Get results

(2) A private member of the reflected object:

General private properties are less used, so let's take a private field as an example, or the example above:

        Static voidMain (string[] args) {            //Reflection DLLs            varStrdllpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Dll\\reflectordll.dll"); varoassembly =Assembly.loadfile (Strdllpath); varLsttypes =oassembly.gettypes (); foreach(varOtypeinchlsttypes) {                if(Otype.name = =" Person")                {                    //all public fields below the class are given by default                    varLstfield = Otype.getfields (BindingFlags.NonPublic |bindingflags.instance); foreach(varOfieldinchLstfield) {Console.WriteLine ("the GetFields () method gets the name of the member:"+ofield.name);        }}} Console.readkey (); }

(3) A static member of the reflected object:

        Static voidMain (string[] args) {            //Reflection DLLs            varStrdllpath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,"Dll\\reflectordll.dll"); varoassembly =Assembly.loadfile (Strdllpath); varLsttypes =oassembly.gettypes (); foreach(varOtypeinchlsttypes) {                if(Otype.name = =" Person")                {                    //all public members below the class are given by default                    varLstmembers = Otype.getmembers (bindingflags.public|bindingflags.static); foreach(varOmeminchlstmembers) {Console.WriteLine ("the GetMembers () method gets the name of the member:"+omem.name); } Console.WriteLine (""); //all public fields below the class are given by default                    varLstfield = Otype.getfields (BindingFlags.NonPublic |bindingflags.instance); foreach(varOfieldinchLstfield) {Console.WriteLine ("the GetFields () method gets the name of the member:"+ofield.name);        }}} Console.readkey (); }

There are enumerated types, and so on, not all introduced, basically is in BindingFlags this above to do processing.

(4) The actions of the object and the object are reflected:

There are two main ways to get objects reflected

         Public StaticT getmodel<t>(T omodel) {varModel =default(T); //get the object method one:Model = (T)typeof(T). GetConstructor (NewSystem.type[] {}). Invoke (New Object[] { });//reflection gets the entity of the generic class//two ways to get the object:Model = (T) activator.createinstance (typeof(T)); //Logical Processing ...                        returnmodel; }

Value and assignment of object properties:

        //List Collection converted to DataTable         Public StaticDataTable listfilltable (Objectobj) {            if(! (obj isIList)) {                return NULL; }            varObjlist = obj asIList; if(Objlist = =NULL|| Objlist. Count <=0)            {                return NULL; }            varTtype = objlist[0]; DataTable DT=NewDataTable (Ttype.gettype ().            Name);            DataColumn column;            DataRow Row; System.reflection.propertyinfo[] Mypropertyinfo= Ttype.gettype (). GetProperties (BindingFlags.Public |bindingflags.instance); foreach(varTinchobjlist) {                if(T = =NULL)                {                    Continue; } row=dt.                NewRow ();  for(inti =0, j = mypropertyinfo.length; I < J; i++) {System.Reflection.PropertyInfo pi=Mypropertyinfo[i]; stringName =Pi.                    Name; if(dt. Columns[name] = =NULL)                    {                        varColtype =Pi.                        PropertyType; if(Coltype. Name = ="Nullable ' 1")                        {                            //Coltype = typeof (System.DBNull);Column =NewDataColumn (name); }                        Else{column=NewDataColumn (name, Coltype); } dt.                    Columns.Add (column); } Row[name]= Pi. GetValue (T,NULL); } dt.            Rows.Add (row); }            returnDT; }

C # Basic Series-Reflection notes

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.