. NET reflection Type class,. net Reflection type
I don't know if you have such a code.
Type type = typeof (T); // T is the input Type
In this way, reflection is used in potential scenarios. Whether you know it or not, it is a fact.
Type is an abstract class and must be instantiated. typeof is the object that returns this instantiation. It meets the Type requirements and provides the ability to access objects, including attributes and methods, fields. CorrespondingFieldInfo, PropertyInfo, and MethodInfoAnd MemberInfo. Their relationship is MemberInfo as the base class, and other classes inherit it.
The above is an introduction. Let's look at an example to get the object description.
Type reflection to obtain attributes (descriptions, etc)
Here, we define a class [5-year indicator] and add the attribute Description, which uses the extended feature class.Description. I will not elaborate here.
Public class FiveYear {// <summary> // Indicator Name // </summary> [Description ("Indicator Name")] public string IndicatorName {get; set ;} /// <summary> /// Indicator Display name /// </summary> [Description ("indicator display name")] public string IndicatorDisplayName {get; set ;} /// <summary> /// metric value of the first year /// </summary> [Description ("Metric value of the first year")] public decimal FirstYearValue {get; set ;} /// <summary> /// indicator value for the next year /// </summary> [Description ("indicator for the next year")] public decimal SecondYearValue {get; set ;} /// <summary> /// indicator value of the third year /// </summary> [Description ("indicator value of the third year")] public decimal ThirdYearValue {get; set ;} /// <summary> /// indicator value of the fourth year /// </summary> [Description ("indicator value of the fourth year")] public decimal ForthYearValue {get; set ;} /// <summary> /// metric value of the fifth year /// </summary> [Description ("Metric value of the fifth year")] public decimal incluthyearvalue {get; set ;}}
We obtain the attribute names and descriptions of the attributes through reflection.
First passAssembly reflects the current Assembly
Assembly demoAssebly = Assembly. getExecutingAssembly (); Type fiveYears = typeof (FiveYear); // get the current instance Object fiveyearObject = demoAssebly. createInstance (fiveYears. fullName); // create the Instance Object PropertyInfo [] properties = fiveyearObject. getType (). getProperties (BindingFlags. instance | BindingFlags. public); // obtain the Public attribute string tStr = string of the Instance Object. empty; tStr + = string. format ("Class Name: {0}", fiveYears. name); foreach (var item in properties) {string name = item. name; // Name object value = item. getValue (obj2, null); // value string des = (DescriptionAttribute) Attribute. getCustomAttribute (item, typeof (DescriptionAttribute ))). description; // if (item. propertyType. isValueType | item. propertyType. name. startsWith ("String") {tStr + = string. format ("\ n attribute name: {0} corresponding value: {1} attribute display name: {2},", name, value, des );}}
The obtained information is displayed
Reflection creates an object
The purpose of reflection is not only to obtain the information corresponding to an object, but also to dynamically create an object and call the object method.
Add a static method to the class.
public static void Add(int x, int y){ int total = x + y; Console.WriteLine(string.Format("【Add】 {0} plus {1} equals to {2}",x,y,total ));}
There are two methods to call a class:
Type 1 InvokeMember ()
2 GetMethond ()
Then, find your own method based on the method signature.
Instance code
Type fiveYears = typeof (FiveYear); object [] paramters = {12, 3}; // create the parameter fiveYears. invokeMember (fiveYears. getMethod ("Add "). name, BindingFlags. invokeMethod, null, fiveYears, paramters );
Public objectInvokeMember (string name, BindingFlags invokeAttr, Binder binder, objecttarget, object [] args );
Note:
FiveYears. GetMethod ("Add"). Name: Obtain the signature of the method.
The third parameter Binder encapsulates the rules for binding objects. It is almost always null and uses the built-in DefaultBinder.
Summary:
The use of reflection can reduce the amount of code to a large extent, the reuse rate is also improved, and flexibility is also good, but sometimes it cannot avoid efficiency issues. This still depends on the situation. The preceding two points are commonly used methods, especially calling methods or attributes by name. You are welcome to give us some advice.
How to Use reflection to get the type
There are four methods:
1. Use the static method GetType (): Type t = Type. GetType ("Class Name string") provided by the Type class ");
2. Use the typeof OPERATOR: Type t = typeof ("Class Name string ");
3. Get the Type object through the Type instance: Type t = instance. GetTye ();
4. obtain from the currently running Assembly: Type type = Assembly. GetExecutingAssembly (). GetType ("Class Name string ");
C # How to create an instance with the class name
What you are talking about is a "reflection" knowledge point. Reflection is supported in Java and. NET, and not all languages support it. For example, C ++ has no reflection.
Reflection actually uses the metadata of the Assembly.
There are many ways to perform Reflection. When writing a program, pilot the System. Reflection namespace. Suppose you want to reflect the class in a DLL without referencing it (that is, unknown type ):
Assembly assembly = Assembly. LoadFile ("Assembly path, cannot be relative path"); // load the assembly (EXE or DLL)
Object obj = assembly. CreateInstance ("fully qualified class name (including namespace)"); // create a class instance
To reflect the classes in the current project, you can:
Assembly assembly = Assembly. GetExecutingAssembly (); // get the current Assembly
Object obj = assembly. CreateInstance ("fully qualified class name (including namespace)"); // creates a class instance and returns the object type, which requires forced type conversion.
It can also be:
Type type = Type. GetType ("Full qualified name of the class ");
Object obj = type. Assembly. CreateInstance (type );
========================================================== ====================
Supplement:
1) when reflecting the creation of an instance of a class, you must ensure that the fully qualified name (namespace + class name) of the class is used ). If the Type. GetType method returns null, the related information in the search metadata fails (reflection fails). Make sure to use the fully qualified name of the class during reflection.
2) The reflection function is very powerful and there is nothing to do. If you implement what you call "cross-assembly", use the first method I have given to create a class instance and reflect the fields, attributes, methods, and events of the instance... and then call it dynamically.