A summary of basic application Examples of C # reflection

Source: Internet
Author: User

This article will reflect the things collated a bit, provide the most comprehensive things, of course, is the basis of things,

On the basis of learning all this, you can learn the specific plug-in reflection of the application first we set up a class library, it was born into Reflectprj. dll,


The code is as follows:

Using System;

Using System.Collections.Generic;

Using System.Text;

Namespace Reflectprj

{

<summary>

Interface

</summary>

public interface Interface1

{

int Add (int num);

int Add ();

}

<summary>

class to be tested

</summary>

public class Reflecttest:interface1

{

public string Writea;

public string Writea

{

get {return writea;}

set {Writea = value;}

}

public string Writeb;

public string Writeb

{

get {return writeb;}

set {writeb = value;}

}

Public Reflecttest ()

{

this. Writea = "Writea";

this. Writeb = "Writeb";

}

Public Reflecttest (String A, string b)

{

this. Writea = A;

this. Writeb = b;

}

public int Add ()

{

return 100;

}

public int Add (int num)

{

return num;

}

public string WriteString (string a,string b)

{

Return "Welcome," + A + "--" +b;

}

public static string Writename (string s)

{

Return "Welcome," + S;

}

public string Writenopara ()

{

Return "You are using a parameterless Method! ” ;

}

private String Writeprivate ()

{

Return "Method of private type!";

}

}

}

Then build a project to introduce the REFLECTPRJ. dll.


The code is as follows:

Using System;

Using System.Collections.Generic;

Using System.Text;

Using Reflectprj;

Using System.Threading;

Using System.Reflection;

Namespace Reflectprjtest

{

Class Myreflecttest

{

Create a delegate

Delegate string testdelegate (string a,string b);

static void Main (string [] args)

{

Assembly assembly= Assembly. Load ("Reflectprj");

foreach (Type var in assembly. GetTypes ())

{

Console. WriteLine (var. Name);//Display all classes under the DLL

}

//*******************************************************

Module [] modules = assembly. GetModules ();

foreach (module module in modules)

{

Console. WriteLine (module/component) name: +module. Name);

}

//*******************************************************

Get the type of the specific class

Type a = typeof (Reflectprj.reflecttest);

Console. WriteLine (A.name);

//*******************************************************

a--create an instance of the type--here is an instance of the constructor with the parameter

string [] Paras ={"AAA", "BBB"};

Creates an instance of the class, followed by a parameter of the Paras constructor--and this obj is an instance of type a

This instance invokes a constructor with a parameter

Object obj = Activator. CreateInstance (A,paras);

Get the properties of an object

Console. WriteLine ("Get the properties of object A:");

foreach (Object var in a.getproperties ())

{

Console. WriteLine (var. ToString ());

}

MethodInfo [] Miarr = A.getmethods ();

Console. WriteLine ("Show All Common methods:");

Show all the common methods

foreach (MethodInfo method in Miarr)

{

Console. WriteLine (method. Name);

}

//************************************************************

Show the specific method

Console. WriteLine ("Show the specific Method! ” );

1. Use of a method with parameters

MethodInfo mi = a.getmethod ("WriteString");

String Mireturn = (string) mi. Invoke (obj, new Object [] {"Using a non-static method with parameters", "2"});

Console. WriteLine ("-" +mi. Name+ "return value:" +mireturn);

2. method calls with no parameters

Console. WriteLine ("Call of method without parameters:");

MethodInfo Minopara = A.getmethod ("Writenopara");

String Minoparareturn = (string) minopara.invoke (obj, null);

Console. WriteLine ("-" +minoparareturn);

3. Use of private type methods

Console. WriteLine ("Use of private type methods:");

MethodInfo miprivate = A.getmethod ("Writeprivate", BindingFlags. Instance | BindingFlags. nonpublic);

String Miprivatereturn = (string) miprivate.invoke (obj, null);

Console. WriteLine ("-" +miprivatereturn);

Console. WriteLine ("Use of *********************** attribute **********************");

4. Get the properties of an object

PropertyInfo [] Propertys = A.getproperties (BindingFlags. Instance | BindingFlags. NonPublic | BindingFlags. public);

5. Show All property names

Console. WriteLine ("All property names for the object are as follows:");

foreach (PropertyInfo Pro in Propertys)

{

Console.WriteLine (Pro. Name);

Gets the initial value of the property

Console. WriteLine (pro. Name+ ":" +pro. GetValue (Obj,null));

Re-assign a value to a property

Pro. SetValue (obj, "Zhang Sanfeng", null);

Console. WriteLine (pro. Name + ":" + Pro. GetValue (obj, null));

}

6. Gets the specified property, and assigns a value

PropertyInfo propertyinfo=a.getproperty ("Writea", BindingFlags. instance| BindingFlags. nonpublic| BindingFlags. public);

Propertyinfo.setvalue (obj, "tulip", null);

Console. WriteLine (propertyinfo.name+ ":" +propertyinfo.getvalue (Obj,null));

Console. WriteLine ("Use *********************** of *********************fieldinfo-public Fields");

7. Field Usage--only get public fields

FieldInfo f1 = A.getfield ("Writea", BindingFlags. instance| BindingFlags. nonpublic| BindingFlags.Public);

Console. WriteLine (F1. GetValue (obj));

Try

{

Reflectprj.reflecttest test = new Reflecttest ("Marry", "Jack");

Type myreflect = typeof (Reflecttest);

FieldInfo field1= Myreflect.getfield ("Writea", BindingFlags. Public | BindingFlags. NonPublic | BindingFlags. Instance);

Console. WriteLine (field1. GetValue (test));

}

catch (Exception ex)

{

Console. WriteLine (ex. Message);

}

//*******************************************************

8. Use of constructors

Console. WriteLine ("Get the form of a constructor");

ConstructorInfo [] cis =a.getconstructors ();

foreach (ConstructorInfo ci in CIS)

{

Console. WriteLine ("form of the constructor:" +ci. ToString ());//Get the form of a constructor

Console. WriteLine ("constructor name:" +ci. Name);

}

Print a form with a parameter constructor

ConstructorInfo ascsingle = a.getconstructor (new Type [] {typeof (String), typeof (String)});

Console. WriteLine (Ascsingle.tostring ());

//****************************************************

9. Factory mode

Console. WriteLine (A.name);

Reflectprj.interface1 reflectObj2 = (Interface1) assembly. CreateInstance ("Reflectprj.reflecttest");

Reflectprj.reflecttest reflectObj1 = (reflecttest) assembly. CreateInstance ("Reflectprj.reflecttest");

Console. WriteLine (Reflectobj2.add ());//typical Factory mode, used in the subsequent real application is the method in the interface (and the interface is implemented by the implementation of the interface Class)

Console. WriteLine (Reflectobj1.writenopara ());

10 Factory mode-overloading of methods

int num = 300;

Console. WriteLine (Reflectobj1.add (300));

Console. WriteLine ("Factory mode is again implemented!") ” );

foreach (Type type in assembly. GetTypes ())

{

if (type. GetInterface ("Reflectprj.interface1")!=null)

{

Implemented by the interface's implementation class

Reflectprj.interface1 interfaceObj3 = (Interface1) Activator. CreateInstance (a);

Console. WriteLine (Interfaceobj3.add ());

Console. WriteLine (Interfaceobj3.add (600));

}

}

//****************************************************

11. A simple example of dynamically creating a delegate binds a delegate to the target method

Testdelegate Mymothod = (testdelegate) Delegate. CreateDelegate (typeof (Testdelegate), obj,mi);

Console. WriteLine (Mymothod.invoke ("Tom", "Jack"));

//****************************************************

B ———-. Use of parameterless constructors

Console. WriteLine ("Use of parameterless constructors!") ” );

Objnonepara is an object produced by the constructor of the Reflecttest class

Object Objnonepara = Activator. CreateInstance (a);

String info= ((reflectprj.reflecttest) Objnonepara). Writenopara ();

Console. WriteLine (info);

PropertyInfo Prowritea = A.getproperty (((reflecttest) Objnonepara). Writea);

Console. WriteLine (Prowritea.getvalue (objnonepara,null));

Prowritea.setvalue (Objnonepara, "Little Tulip", null);

Console. WriteLine (Prowritea.getvalue (Objnonepara, null));

C: ——— Use the constructor of the parameter again to generate the instance

Reflecttest Objpara = (reflecttest) Activator. CreateInstance (A, new object [] {"Xiao Yu", "Come"});

Console. WriteLine (objpara.writea+ "/t" +objpara.writeb);

Console. WriteLine (Objpara.writenopara ());

Calling a method with parameters

Console. WriteLine (objpara.writestring ("Great Yu", "Go home!") ” ));

MethodInfo Mymi=a.getmethod ("writestring");

The specified method of binding the delegate dynamically using the delegate

Mymothod= (testdelegate) Delegate. CreateDelegate (typeof (Testdelegate), Objpara,mymi);

Console. WriteLine ("Mymothod.invoke", "Happy year of the Ox!") ” ));

Screen paused

Console. ReadLine ();

}

}

}

I hope this article is helpful to everyone's C # programming.

In addition to the Declaration, Running GuestArticles are original, reproduced please link to the form of the address of this article
A summary of basic application Examples of C # reflection

This address: http://www.paobuke.com/develop/c-develop/pbk23450.html






Related Content C # mask due to crash popup windows exception box C # socket Implementation UDP Protocol Communication sample Code C # determine if a string is int/double (instance) TortoiseSVN use tutorial
C # Programming implementation get the file name of all files in a folder C # program optimization-effectively reduce CPU usage based on the C # implementation of one of the simplest HTTP server instances C #, vb.net, and SQL method to determine whether a specified year is a leap years

A summary of basic application Examples of C # reflection

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.