. NET reflection Type class

Source: Internet
Author: User

. NET reflection Type class

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 {////// Indicator Name ///[Description ("Indicator Name")] public string IndicatorName {get; set ;}////// Metric display name ///[Description ("Metric display name")] public string IndicatorDisplayName {get; set ;}////// Metric value for the first year ///[Description ("first-year indicator")] public decimal FirstYearValue {get; set ;}////// Metric value for the next year ///[Description ("Metric value of the next year")] public decimal SecondYearValue {get; set ;}////// Metric value for the third year ///[Description ("third-year indicator")] public decimal ThirdYearValue {get; set ;}////// Metric value for the fourth year ///[Description ("")] public decimal ForthYearValue {get; set ;}////// Metric value for the fifth year ///[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. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + expires + CjxwcmUgY2xhc3M9 "brush: java;"> 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.

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.