The Assembly contains modules, while the module contains types and types including members. Reflection provides encapsulated assembly, module, and type objects. You can use reflection to dynamically create instances of the type, bind the type to an existing object, or obtain the type from an existing object. Then, you can call methods of the type or access its fields and attributes. Reflection is usually used for the following purposes:
Use Assembly to define and load an Assembly, load the modules listed in the Assembly list, locate the type in this Assembly, and create instances of this type.
Use Module to learn the following similar information: including the Module assembly and classes in the Module. You can also obtain all global methods defined on the module or other specific non-Global methods.
Use ConstructorInfo to learn the following information: name, parameter, access modifier (such as public or private) and implementation details (such as abstract or virtual) of the ConstructorInfo. Use the GetConstructors or GetConstructor method of Type to call a specific constructor.
Learn the following information using MethodInfo: method name, return type, parameter, access modifier (such as public or private), and implementation details (such as abstract or virtual. Use the GetMethods or GetMethod method of Type to call a specific method.
Use FieldInfo to learn the following information: field name, access modifier (such as public or private), implementation details (such as static), and so on; and obtain or set the field value.
Use EventInfo to learn the following similar information: event name, event handler data type, custom attribute, declaration type, and reflection type, and add or remove event handlers.
Use PropertyInfo to learn the following similar information: attribute name, data type, declaration type, reflection type, read-only or writable status, and get or set the attribute value.
Use ParameterInfo to learn the following similar information: Parameter Name, data type, whether the parameter is an input parameter or an output parameter, and the position of the parameter in the method signature.
When you work in only reflection context of an application domain, use CustomAttributeData to learn about custom attributes. With CustomAttributeData, you do not have to create Attribute instances to check them. [FROM: MSDN]
An example is provided to briefly describe:
Using System;
Using System. Reflection;
Namespace testReflection
{
Public delegate void TestDelegate (string info );
Class Program
{
Static void Main (string [] args)
{
// Load from Dll
// Assembly ass = Assembly. LoadFile (@ "TestReflect. dll ");
// Type myType = ass. GetType ("testReflection. Person ");
// Object aPerson = ass. CreateInstance ("Person ");
// Obtain the type
Type myType = Type. GetType ("testReflection. Person ");
// Parameters used by the constructor
Object [] constuctParms = new object [] {"Brad Pitt "};
// Create an instance
// Object TestName = Assembly. GetAssembly (myType). CreateInstance ("Person ");
Object aPerson = Activator. CreateInstance (myType, constuctParms );
// Call the method using MethodInfo and Invoke
MethodInfo displayInfoMethod = myType. GetMethod ("DisplayInfo ");
DisplayInfoMethod. Invoke (aPerson, new object [] {"Using Invoke to call Method DisplayInfo ()"});
// Call the method using InvokeMember
// Some flag spaces of the call Method
BindingFlags flag = BindingFlags. InvokeMethod | BindingFlags. Public | BindingFlags. Instance;
MyType. InvokeMember ("DisplayInfo", flag, null, aPerson, new object [] {"Using InvokeMethod to call DisplayInfo ()"});
// If the method returns a value
String name = (string) myType. InvokeMember ("getName", flag, null, aPerson, null );
System. Console. WriteLine ("call getName (), return:" + name );
// Set the attribute value
MyType. InvokeMember ("Age", BindingFlags. SetProperty, null, aPerson, new object [] {30 });
// Obtain the property value
Int age = (int) myType. InvokeMember ("Age", BindingFlags. GetProperty, null, aPerson, null );
System. Console. WriteLine ("Get the property of Age:" + Convert. ToString (age ));
// Set the field value
MyType. InvokeMember ("Name", BindingFlags. SetField, null, aPerson, new object [] {"Michal Jodn "});
// Obtain the field value
String fname = (string) myType. InvokeMember ("Name", BindingFlags. GetField, null, aPerson, null );
System. Console. WriteLine ("Get the Field Value of Name:" + fname );
MyType. InvokeMember ("DisplayName", flag, null, aPerson, null );
// Obtain the method set
MethodInfo [] methods = myType. GetMethods ();
Foreach (MethodInfo m in methods ){
System. Console. WriteLine (m. Name );
}
// The methods include GetFiedls (), GetProperties (), and GetEvents ().
// Use Delegate
// This method is static, so the delegate type must be provided.
TestDelegate dg = (TestDelegate) Delegate. CreateDelegate (typeof (testReflection. TestDelegate), aPerson, "DisplayInfo ");
Dg ("Test Delegate by call DisplayInfo ()");
// Obtain all the assemblies of the Solution
Assembly [] AX = AppDomain. CurrentDomain. GetAssemblies ();
// Display the name of each Assembly through Traversal
Foreach (object var in AX ){
Console. WriteLine ("Assembly name:" + var. ToString ());
}
// Use a known Assembly name to create an Assembly
// Display the location of the initial specified Assembly through the CodeBase attribute
Console. WriteLine ("Location of the initially specified Assembly TestReflection:" + Assembly. Load ("TestReflection"). CodeBase );
System. Console. ReadLine ();
}
}
Public class Person
{
Public string Name;
Private int _ Age;
Public int Age
{
Get
{
Return _ Age;
}
Set
{
_ Age = value;
}
}
Public Person (string Name)
{
This. Name = Name;
}
Public void DisplayInfo (string info)
{
System. Console. WriteLine (info );
System. Console. WriteLine ("called sucessfully! ");
}
Public void DisplayName ()
{
System. Console. WriteLine (Name );
}
Public string getName ()
{
Return Name;
}
}
}
Note:
To use reflection to dynamically call class members, you need a method of the Type class: InvokeMember. The statement for this method is as follows:
Public object InvokeMember (
String name,
BindingFlags invokeAttr,
Binder binder,
Object target,
Object [] args
);
Parameters
Name
String, which contains the name of the constructor, method, attribute, or field member to be called.
-Or-
An empty string ("") indicates the default Member of the call.
InvokeAttr
One-bit blocking is composed of one or more BindingFlags that specify the search execution method. Access can be one of BindingFlags, such as Public, NonPublic, Private, InvokeMethod, and GetField. You do not need to specify the search type. If the search type is omitted, BindingFlags. Public | BindingFlags. Instance will be applied.
Binder
A Binder object that defines a set of attributes and enables binding. Binding may involve selecting overload methods, mandatory parameter types, and calling members through reflection.
-Or-
If it is a null reference (Nothing in Visual Basic), DefaultBinder is used.
Target
Call the Object of the specified member on it.
Args
An array containing parameters passed to the member to be called.
Return Value
Indicates the Object returned by the called member.
The following BindingFlags filter flag can be used to define members included in the search:
To obtain the returned value, BindingFlags. Instance or BindingFlags. Static must be specified.
Specify BindingFlags. Public to include Public members in the search.
Specify BindingFlags. NonPublic to include non-public members (Private Members and protected members) in the search ).
Specify BindingFlags. FlattenHierarchy to include static members in the hierarchy.
The following BindingFlags modifier can be used to change the search execution method:
BindingFlags. IgnoreCase, indicating that the name case is ignored.
BindingFlags. DeclaredOnly: searches for members declared on the Type, rather than simply inherited members.
The following BindingFlags call flag can be used to indicate the operations to be performed on members:
CreateInstance, indicating to call the constructor. Ignore name. Invalid for other call flag.
InvokeMethod indicates that a method is called, instead of a constructor or an initial value of the type.
It is invalid for SetField or SetProperty.
GetField indicates obtaining the field value. It is invalid for SetField.
SetField, indicating to set the field value. Invalid for GetField.
GetProperty indicates obtaining the property. It is invalid for SetProperty.
SetProperty indicates setting properties. Invalid for GetProperty.