. NET reflection Type class,. net Reflection type

Source: Internet
Author: User

. NET reflection Type class,. net Reflection type

I don't know if you have such a code.

 

?
1 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.

 

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344 public class FiveYear    {        /// <summary>        /// Indicator Name        /// </summary>        [Description("Indicator Name")]        publicstring IndicatorName { get; set; }         /// <summary>        /// Metric display name        /// </summary>        [Description("Metric display name")]        publicstring IndicatorDisplayName { get; set; }         /// <summary>        /// Metric value for the first year        /// </summary>        [Description("Metric value for the first year")]        publicdecimal FirstYearValue { get; set; }         /// <summary>        /// Metric value for the next year        /// </summary>        [Description("Metric value for the next year")]        publicdecimal SecondYearValue { get; set; }         /// <summary>        /// Metric value for the third year        /// </summary>        [Description("Third-year indicator value")]        publicdecimal ThirdYearValue { get; set; }         /// <summary>        /// Metric value for the fourth year        /// </summary>        [Description("Metric value for the fourth year")]        publicdecimal ForthYearValue { get; set; }         /// <summary>        /// Metric value for the fifth year        /// </summary>        [Description("Metric value for the fifth year")]        publicdecimal FifthYearValue { get; set; }    }

 

 

We obtain the attribute names and descriptions of the attributes through reflection.

First passAssembly reflects the current Assembly

 

?
123456789101112131415 Assembly demoAssebly= Assembly.GetExecutingAssembly();Type fiveYears = typeof(FiveYear);// Obtain the current instanceObject  fiveyearObject= demoAssebly.CreateInstance(fiveYears.FullName);// Create an Instance ObjectPropertyInfo[] properties = fiveyearObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);// Obtain the public attributes of the Instance Objectstring tStr=string.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;// Attribute Value    if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))                {                    tStr += string.Format("\ N property name: {0} corresponding value: {1} property 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, method of calling the object <symbol "http://www.2cto.com/kf/ware/vc/" target = "_ blank" class = "keylink"> vcD4KPHA + character + 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

 

?
123 Type fiveYears =typeof(FiveYear);object[] paramters = { 12, 3 };// Create parametersfiveYears.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.

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.