C # core syntax-Reflection (reflection type, method, constructor, attribute, configurable and scalable, complete reflection encapsulation of Database Class ),

Source: Internet
Author: User

C # core syntax-Reflection (reflection type, method, constructor, attribute, configurable and scalable, complete reflection encapsulation of Database Class ),

Reflection is. NET. through reflection, you can obtain information about members and members of every type (including class, structure, Delegate, interface, and enumeration) in a program or set at runtime. With reflection, you can be familiar with every type. In addition, I can directly create an object even if the object type is unknown during compilation.

Purpose of reflection:
(1) Use Assembly to define and load the Assembly, load the module in the Assembly list, and locate the type in this Assembly and create instances of this type.
(2) Use the Module to understand the Assembly containing the Module and the classes in the Module, and obtain all global methods or other specific non-Global methods defined on the Module.
(3) Use ConstructorInfo to understand the name, parameters, access modifiers (such as pulic or private) and implementation details (such as abstract or virtual) of the ConstructorInfo.
(4) use MethodInfo to understand the method name, return type, parameters, access modifiers (such as pulic or private), and implementation details (such as abstract or virtual.
(5) Use FiedInfo to learn the field name, access modifier (such as public or private), implementation details (such as static), and obtain or set the field value.
(6) Use EventInfo to learn about the event name, event handler data type, custom attributes, declaration type, and reflection type, and add or remove event handlers.
(7) Use PropertyInfo to understand the attribute name, data type, declaration type, reflection type, read-only or writable status, and obtain or set the attribute value.
(8) Use ParameterInfo to know the parameter name, data type, input parameter, output parameter, and the parameter location in the method signature.

Namespace used for reflection:
System. Reflection
System. Type
System. Reflection. Assembly

Main classes used for reflection:
System. Type class -- this class can be used to access information of any given data Type.
System. Reflection. Assembly class -- it can be used to access the information of a given Assembly or load the Assembly into the program.

System. TypeClass:
The System. Type class plays a core role in reflection. But it is an abstract base class. Type has a derived class corresponding to each data Type. We use the methods, fields, and attributes of the object of this derived class to find all information about this Type.
There are three common methods to obtain Type references of a given Type:
UseC # typeofOperator.
Type t = typeof (string );
Objects usedGetType ()Method.
String s = "grayworm ";
Type t = s. GetType ();
 
You can also callTypeClass static methodGetType ().
Type t = Type. GetType ("System. String ");

The above three types of code obtain the Type of the string Type. After the Type of the string Type is referenced with t, we can use t to detect the structure of the string Type.
String n = "grayworm ";
Type t = n. GetType ();
Foreach (MemberInfo mi in t. GetMembers ())
{
Console. WriteLine ("{0}/t {1}", mi. MemberType, mi. Name );
}

TypeClass attributes:
Name Data Type Name
Full qualified name of FullName data type (including namespace name)
Namespace: Namespace name that defines the data type
IsAbstract indicates whether this type is an abstract type.
IsArray indicates whether this type is an array.
IsClass indicates whether this type is a class
IsEnum indicates whether this type is Enumeration
IsInterface indicates whether this type is an interface
IsPublic indicates whether this type is public
IsSealed indicates whether this type is a seal class
IsValueType indicates whether this type is a value type.
TypeClass method:
GetConstructor (), GetConstructors (): returns the ConstructorInfo type, which is used to obtain information about the ConstructorInfo class.
GetEvent (), GetEvents (): returns the EventInfo type, used to obtain the event information of this class.
GetField (), GetFields (): returns the FieldInfo type, used to obtain information about the fields (member variables) of this class.
GetInterface (), GetInterfaces (): returns the InterfaceInfo type, used to obtain information about interfaces implemented by this class.
GetMember (), GetMembers (): returns the MemberInfo type, used to obtain information about all members of this class.
GetMethod (), GetMethods (): return the MethodInfo type, used to obtain information about the method of this class
GetProperty (), GetProperties (): returns the PropertyInfo type, which is used to obtain the property information of this class.
You can call these members by calling the InvokeMember () method of Type, or by calling the Invoke () method of MethodInfo, PropertyInfo and other classes.

View the constructor in the class:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
ConstructorInfo [] ci = t. GetConstructors ();// Obtain all constructors of the class
Foreach (ConstructorInfo c in ci) // traverses each Constructor
{
ParameterInfo [] ps = c. GetParameters ();// Retrieve all parameters of each Constructor
Foreach (ParameterInfopi in ps) // Print and traverse all parameters of the constructor.
{
Console. Write (pi. ParameterType. ToString () + "" + pi. Name + ",");
}
Console. WriteLine ();
}

Use constructors to dynamically generate objects:
Type t = typeof (NewClassw );
Type [] pt = newType [2];
Pt [0] = typeof (string );
Pt [1] = typeof (string );
// Obtain the constructor Based on the parameter type
ConstructorInfo ci = t. GetConstructor (pt ); 
// Construct an Object array as the input parameter of the constructor.
Object [] obj = newobject [2] {"grayworm", "hi.baidu.com/grayworm "};
// Call the constructor to generate an object
Object o = ci. Invoke (obj ); 
// Call the method of the generated object to test whether the object is successfully generated
// (NewClassw) o). show ();

UseActivatorGenerated object:
Type t = typeof (NewClassw );
// Constructor Parameters
Object [] obj = new object [2] {"grayworm", "hi.baidu.com/grayworm "};
// Use the CreateInstance static method of Activator to generate a new object
Object o = Activator. CreateInstance (t, "grayworm", "hi.baidu.com/grayworm "); 
// (NewClassw) o). show ();

View attributes in the class:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
PropertyInfo [] pis = t. GetProperties ();
Foreach (PropertyInfo pi inpis)
{
Console. WriteLine (pi. Name );
}

ViewPublicMethod:
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
MethodInfo [] mis = t. GetMethods ();
Foreach (MethodInfo mi inmis)
{
Console. WriteLine (mi. ReturnType + "" + mi. Name );
}

ViewPublicField
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
FieldInfo [] FCM = t. GetFields ();
Foreach (FieldInfo fi in FCM)
{
Console. WriteLine (fi. Name );
} (Http://hi.baidu.com/grayworm)

Generate an object Using Reflection and call properties, methods, and fields for operations 
NewClassw nc = new NewClassw ();
Type t = nc. GetType ();
Object obj = Activator. CreateInstance (t );
// Obtain the ID field
FieldInfo fi = t. GetField ("ID ");
// Assign a value to the ID field
Fi. SetValue (obj, "k001 ");
// Obtain the MyName attribute
PropertyInfo pi1 = t. GetProperty ("MyName ");
// Assign a value to the MyName attribute
Pi1.SetValue (obj, "grayworm", null );
PropertyInfo pi2 = t. GetProperty ("MyInfo ");
Pi2.SetValue (obj, "hi.baidu.com/grayworm", null );
// Obtain the show Method
MethodInfo mi = t. GetMethod ("show ");
// Call the show Method
Mi. Invoke (obj, null );

System. Reflection. AssemblyClass 
The Assembly class can obtain the Assembly information, dynamically load the Assembly, find the type information in the Assembly, and create instances of this type.
Using the Assembly class can reduce the coupling between the Assembly and facilitate the rationalization of the software structure.

Returned by Assembly nameAssemblyObject
Assembly ass = Assembly. Load ("ClassLibrary831 ");
PassDLLFile Name returnAssemblyObject
Assembly ass = Assembly. LoadFrom ("ClassLibrary831.dll ");
PassAssemblyObtain classes in an assembly 
Type t = ass. GetType ("ClassLibrary831.NewClass ");//
The parameter must be the full name of the class.
PassAssemblyObtain all classes in the Assembly
Type [] t = ass. GetTypes ();

//Reflection by Assembly name
Assembly ass = Assembly. Load ("ClassLibrary831 ");
Type t = ass. GetType ("ClassLibrary831.NewClass ");
Object o = Activator. CreateInstance (t, "grayworm", "http://hi.baidu.com/grayworm ");
MethodInfo mi = t. GetMethod ("show ");
Mi. Invoke (o, null );

//PassDLLAll types in the full file name reflection
Assembly assembly = Assembly. LoadFrom ("xxx. dllPath");
Type [] aa = a. GetTypes ();

Foreach (Type t in aa)
{
If (t. FullName = "a. B. c ")
{
Object o = Activator. CreateInstance (t );
}
}

There are matching related teaching videos. Youku is transcoding...

 

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.