C # reflection mechanism and method,

Source: Internet
Author: User

C # reflection mechanism and method,

 

Directory:

I. MAIN FEATURES OF REFLECTION

1. A very important Type in reflection is Type.

1) use this method to obtain a Type when no object exists.

2) After an object is obtained, the GetType () method of the object is used to obtain the Type object of the specified object Type.

2. Get all methods in the Person class

3. Get all attributes of a Type

4. Retrieve all fields in the class. Private fields cannot be obtained.

  5. Retrieve all members, excluding private members

Ii. Reflection dynamic assembly loading

1. dynamically load an assembly

2. obtain all types in the just-loaded assembly

1) GetTypes () obtains all types

2) obtain only the public types.

3. Get the Type of a class in the Assembly

4. Dynamic call class Method

1) call a method without parameters or return values

2) Call methods with parameters and returned values

1> call methods without overloading

2> call methods with overload

5. Get the class attributes through reflection and assign values

1) Get the Name attribute

2) assign values to attributes

3) Get the property value

4) Obtain and call the Method

6. manually search for the Type constructor and call this constructor to create the type object.

Iii. Other reflection methods

1. bool IsAssignableFrom (Type c) determines whether the current Type of variable can accept the value assignment of the c Type variable.

2. bool IsInstanceOfType (object o): determines whether the object o is an instance of the current class (the current class can be an o class, parent class, interface)

3. bool IsSubclassOf (Type c): determines whether the current class is a subclass of class c.

4. IsAbstract: determines whether it is abstract, including interfaces.

----------------------------------------------------------------------------

 

What is reflection?

Reflection: The process of dynamically obtaining an assembly, obtaining the type metadata, and then accessing this type.

I. MAIN FEATURES OF REFLECTION

Before introducing the main features of reflection, we should create a Person class (the following operations are performed on the Person class)

Class Person {public int _ height; public string Name {get; set;} public int Age {get; set;} public string Email {get; set;} public void Say () {Console. writeLine ("Hello everyone! ");} Public void SayMorning () {Console. WriteLine (" Good morning everybody! ");} // Private void Do () {Console. WriteLine (" Just do it! ");}}View Code

1. A very important Type in reflection is Type.

Obtain the Type object of the Person Type (the Type object stores all the information about a certain Type. [A Type object is a Type of "Type metadata"])

You can use either of the following methods to obtain a Type object:

1) use this method to obtain a Type when no object exists.
Type type = typeof (Person );

2) After an object is obtained, the GetType () method of the object is used to obtain the Type object of the specified object Type.
Person p = new Person ();
Type personType = p. GetType ();


2. Get all methods in the Person class

(GetMethods () of the Type object can be used to obtain all methods of the specified Type, including methods automatically generated by the compiler and methods inherited from the parent class, but not private methods)
MethodInfo [] methods = personType. GetMethods ();
For (int I = 0; I <methods. Length; I ++)
{
Console. WriteLine (methods [I]. Name );
}

 

3. Get all attributes of a Type
PropertyInfo [] properties = personType. GetProperties ();
For (int I = 0; I <properties. Length; I ++)
{
Console. WriteLine (properties [I]. Name );
}
Console. ReadKey ();


4. Retrieve all fields in the class. Private fields cannot be obtained.
FieldInfo [] fields = personType. GetFields ();
For (int I = 0; I <fields. Length; I ++)
{
Console. WriteLine (fields [I]. Name );
}
Console. ReadKey ();


5. Retrieve all members, excluding private members
MemberInfo [] members = personType. GetMembers ();
For (int I = 0; I <members. Length; I ++)
{
Console. WriteLine (members [I]. Name );
}
Console. ReadKey ();

Ii. Reflection dynamic assembly loading

When receiving and transmitting dynamic loading assembly, paste the program-level code (the following operations are performed on the Assembly TestDll. dll)

Namespace TestDll {public class Class1 {} class MyClass {public void English () {Console. writeLine ("Hi, English") ;}} public abstract class MyAbstractClass {} public static class MyStaticClass {} public class Person {public Person () {} public Person (string name, int age, string email) {this. name = name; this. age = age; this. email = email;} public string Name {get; set;} public int Age {g Et; set;} public string Email {get; set;} public void GetNameValue () {Console. writeLine (this. name + "--" + this. age + "--" + this. email);} public void English () {Console. writeLine ("Hi, English");} public void China () {Console. writeLine ("Hello, China");} public int Add (int n1, int n2) {return n1 + n2;} public int Add (int n1, int n2, int n3) {return n1 + n2 + n3;} public class Student: Perso N, IFlyable {public string StudentNo {get; set ;}# region IFlyable member public void Fly () {Console. WriteLine ("I can Fly! ") ;}# Endregion} class Teacher: Person {} public delegate void MyDelegate (); delegate void MyDelegate1 (); public enum GoodMan {high, rich, shuai} public interface IFlyable {void Fly ();}}View Code

1. dynamically load an assembly
Assembly assembly = Assembly. LoadFile (@ "D: \ TestDll \ bin \ Debug \ TestDll. dll ");

Note: This address is the absolute address of the program and its location.


2. obtain all types in the just-loaded assembly
Assembly. GetType () is equivalent to typeof (Assembly)
1) GetTypes () obtains all types
Type [] types = assembly. GetTypes ();

2) obtain only the public types.
Type [] types = assembly. GetExportedTypes ();
For (int I = 0; I <types. Length; I ++)
{
Console. WriteLine (types [I]. Name );
}

3. Get the Type of a class in the Assembly
For example, you can only obtain the Type of the Person class.
The GetType () method has an overload. Select the second overload. The parameter indicates the "fully qualified name" of the type to be obtained, that is, namespace. Class Name.
The Type obtained here is equivalent to typeof (Person) or: p. GetType ();
Type personType = assembly. GetType ("_ 02TestDll. Person ");

Get all methods: personType. GetMethods ();

4. Dynamic call class Method

(Borrow the method of the Person class obtained above)

Obtain a specific method (based on the method name): personType. GetMethod ();

1) call a method without parameters or return values

MethodInfo method = personType. GetMethod ("SayHi ");
Console. WriteLine (method. Name );

// Create a Person object through reflection {actually, create a Person object through the Person Type}

Object objPerson = Activator. CreateInstance (personType );

// Call this method
Method. Invoke (objPerson, null );

2) Call methods with parameters and returned values

1> call methods without overloading
// Find the corresponding method
MethodInfo method = personType. GetMethod ("Add ");
Object obj = Activator. CreateInstance (personType );
// Call
Object result = method. Invoke (obj, new object [] {102,203 });
Console. WriteLine ("the returned result of calling the Add method is: {0}", result );
# Endregion


2> call methods with overload

// Find the corresponding method
MethodInfo method = personType. GetMethod ("Add", new Type [] {typeof (int), typeof (int), typeof (int )});
Object obj = Activator. CreateInstance (personType );

// Call
Int r = (int) method. Invoke (obj, new object [] {1, 2, 3 });
Console. WriteLine (r );

5. Get the class attributes through reflection and assign values

(Borrow the method of the Person class obtained above)

1) Get the Name attribute
PropertyInfo property = personType. GetProperty ("Name ");
Object obj = Activator. CreateInstance (personType );
2) assign values to attributes
Property. SetValue (obj, "zhangsan", null );

3) Get the property value
String name = property. GetValue (obj, null). ToString ();
Console. WriteLine (name );

 

4) Obtain and call the Method

MethodInfo method = personType. GetMethod ("GetNameValue ");
Method. Invoke (obj, null );
Console. ReadKey ();


6. manually search for the Type constructor and call this constructor to create the type object.

The corresponding constructor is found, but it has not been called
ConstructorInfo ctor = personType. GetConstructor (new Type [] {typeof (string), typeof (int), typeof (string )});

Start to call the constructor.
Object obj = ctor. Invoke (new object [] {"hpp", 16, "hpp@yahoo.com "});
Console. WriteLine (obj. ToString ());

MethodInfo method = personType. GetMethod ("GetNameValue ");
Method. Invoke (obj, null );
Console. ReadKey ();

Iii. Other reflection methods

// Dynamically load an assembly
Assembly assembly = Assembly. LoadFile (@ "D: \ TestDll \ bin \ Debug \ TestDll. dll ");

// Obtain the Type of the class
Type typePerson = assembly. GetType ("TestDll. Person ");

Type typeStudent = assembly. GetType ("TestDll. Student ");

Type typeIFlyable = assembly. GetType ("TestDll. IFlyable ");

1. bool IsAssignableFrom (Type c) determines whether the current Type of variable can accept the value assignment of the c Type variable.


// It indicates that the Student type can be assigned to the Person type, because the Student type inherits from the Person class.
Bool B = typePerson. IsAssignableFrom (typeStudent); // true

// You can assign the Student type to the IFlyable type because the Student type inherits from the IFlyable interface.

Bool B = typeIFlyable. IsAssignableFrom (typeStudent); // true

// The Person type cannot be assigned to the IFlyable type, because the Person type does not inherit the IFlyable Interface

Bool B = typeIFlyable. IsAssignableFrom (typePerson); // false

2. bool IsInstanceOfType (object o): determines whether the object o is an instance of the current class (the current class can be an o class, parent class, interface)

// Person
Object objPerson = Activator. CreateInstance (typePerson );
// Student
Object objStudent = Activator. CreateInstance (typeStudent );

// The current class is the Person class.

Bool B = typePerson. IsInstanceOfType (objPerson); // true

// The Suntent class is a subclass of the Person class.

Bool B = typePerson. IsInstanceOfType (objStudent); // true

// The person class is not a subclass of Student.

Bool B = typeStudent. IsInstanceOfType (objPerson); // false

3. bool IsSubclassOf (Type c): determines whether the current class is a subclass of class c.

// Person
Object objPerson = Activator. CreateInstance (typePerson );
// Student
Object objStudent = Activator. CreateInstance (typeStudent );

// The Suntent class is a subclass of the Person class.

Bool B = typeStudent. IsSubclassOf (typePerson); // true

// The person class is not a subclass of Student.

Bool B = typePerson. IsSubclassOf (typeStudent); // false

// The returned value is false. Only the parent-child relationship between the class and the class is verified, and the interface does not include.
Bool B = typeStudent. IsSubclassOf (typeIFlyable );

4. IsAbstract: determines whether it is abstract, including interfaces.

Type typeMyAbsClass = assembly. GetType ("TestDll. mydomainactclass ");
Type typeMyStaticClass = assembly. GetType ("TestDll. MyStaticClass ");

Console. WriteLine (typePerson. IsAbstract); // false;
Console. WriteLine (typeStudent. IsAbstract); // false
Console. WriteLine (typeIFlyable. IsAbstract); // true
Console. WriteLine (typeMyAbsClass. IsAbstract); // true
Console. WriteLine (typeMyStaticClass. IsAbstract); // true
Console. ReadKey ();

 

The above are some introductions of reflection and some basic usage of amplification ······

Related Article

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.