The Reflection Characteristics of. NET and the Reflection Characteristics of. NET

Source: Internet
Author: User

The Reflection Characteristics of. NET and the Reflection Characteristics of. NET

In the. net Framework, reflection features are widely used. There are two definitions of reflection.

Natural explanation: radiation is a natural phenomenon, represented by the reverse reaction of the stimulus to the stimulus. This is a literal explanation of reflection. Let's take a look at reflection in computer programming;

Programming explanation: using System. class in the Reflection namespace and System. type. You can obtain information about the loaded assembly and types defined in it (such as classes, interfaces, and value types. You can also use reflection to create a type instance at runtime and call and access these instances.

Reflection has the following purposes: it allows you to view attribute information at runtime; it allows you to review various types in the collection and instantiate these types; it allows delayed binding of methods and properties; it allows creating new types at run time, and then using these types to execute some tasks.

The following describes the source code of attributes and methods related to the reflected assembly:

(1). Object's GetType () method:

    // Returns a Type object which represent this object instance.    //     [System.Security.SecuritySafeCritical]  // auto-generated    [Pure]    [ResourceExposure(ResourceScope.None)]    [MethodImplAttribute(MethodImplOptions.InternalCall)]    public extern Type GetType();

(2). The GetProperty () method of PropertyInfo:

 public PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder,                         Type returnType, Type[] types, ParameterModifier[] modifiers)        {            if (name == null)                throw new ArgumentNullException("name");            if (types == null)                throw new ArgumentNullException("types");            Contract.EndContractBlock();            return GetPropertyImpl(name,bindingAttr,binder,returnType,types,modifiers);        }        public PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers)        {            if (name == null)                throw new ArgumentNullException("name");            if (types == null)                throw new ArgumentNullException("types");            Contract.EndContractBlock();            return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,modifiers);        }        public PropertyInfo GetProperty(String name, BindingFlags bindingAttr)        {            if (name == null)                throw new ArgumentNullException("name");            Contract.EndContractBlock();            return GetPropertyImpl(name,bindingAttr,null,null,null,null);        }        public PropertyInfo GetProperty(String name, Type returnType, Type[] types)        {            if (name == null)                throw new ArgumentNullException("name");            if (types == null)                throw new ArgumentNullException("types");            Contract.EndContractBlock();            return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,null);        }        public PropertyInfo GetProperty(String name, Type[] types)        {            if (name == null)                throw new ArgumentNullException("name");            if (types == null)                throw new ArgumentNullException("types");            Contract.EndContractBlock();            return GetPropertyImpl(name,Type.DefaultLookup,null,null,types,null);        }        public PropertyInfo GetProperty(String name, Type returnType)        {            if (name == null)                throw new ArgumentNullException("name");            if (returnType == null)                throw new ArgumentNullException("returnType");            Contract.EndContractBlock();            return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,null,null);        }        internal PropertyInfo GetProperty(String name, BindingFlags bindingAttr, Type returnType)        {            if (name == null)                throw new ArgumentNullException("name");            if (returnType == null)                throw new ArgumentNullException("returnType");            Contract.EndContractBlock();            return GetPropertyImpl(name, bindingAttr, null, returnType, null, null);        }        public PropertyInfo GetProperty(String name)        {            if (name == null)                throw new ArgumentNullException("name");            Contract.EndContractBlock();            return GetPropertyImpl(name,Type.DefaultLookup,null,null,null,null);        }

(3). Object's GetValue () method:

[DebuggerStepThroughAttribute]        [Diagnostics.DebuggerHidden]        public Object GetValue(Object obj)        {            return GetValue(obj, null);        }        [DebuggerStepThroughAttribute]        [Diagnostics.DebuggerHidden]        public virtual Object GetValue(Object obj,Object[] index)        {            return GetValue(obj, BindingFlags.Default, null, index, null);        }        public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);

The above section describes the source code of the underlying method related to reflection. Now we will introduce more common methods:

(1). Get all the public attributes of the object.

/// <Summary> /// obtain all public attributes of an object. /// </Summary> /// <param name = "obj"> defines the data type of the method. </Param> /// <returns> returns an array containing the property information of the object. </Returns> public static IEnumerable <PropertyInfo> GetProperties (this object obj) {return obj. GetType (). GetProperties ();}

(2). Get the attributes of an object.

/// <Summary> /// obtain the attributes of an object. /// </Summary> /// <param name = "obj"> defines the data type of the method. Gb </param> /// <param name = "flags"> indicates the attribute to be retrieved. </Param> /// <returns> returns an array containing the property information of the object. </Returns> public static IEnumerable <PropertyInfo> GetProperties (this object obj, BindingFlags flags) {return obj. GetType (). GetProperties (flags );}

(3). Use the specified name to obtain the attribute value of the current object with the specified name.

/// <Summary> /// obtain the attribute value of the current object with the specified name. /// </Summary> /// <param name = "obj"> Object of the attribute value to be retrieved. </Param> /// <param name = "propertyName"> name of the property to be retrieved. </Param> // <returns> returns the attribute value. </Returns> public static object GetPropertyValue (this object obj, string propertyName) {var item = obj. getType (). getProperty (propertyName); if (item = null) return null; var value = obj. getType (). getProperty (propertyName ). getValue (obj); if (item. propertyType. isGenericType) {value = item. propertyType. getProperty (propertyName);} return value ;}

(4). Obtain an enumerated string value.

/// <Summary> /// obtain an enumerated string value. /// </Summary> /// <param name = "obj"> the string value returned by this enumeration. </Param> /// <returns> returns an enumerated string value. </Returns> public static string GetStringValue (this System. enum obj) {var fieldInfo = obj. getType (). getField (obj. toString (); var attributes = fieldInfo. getCustomAttributes (typeof (StringValueAttribute), false) as StringValueAttribute []; var output = (StringValueAttribute) attributes. getValue (0); return output. text ;}

(5). Obtain the method call.

/// <Summary> /// obtain method call /// </summary> /// <typeparam name = "T"> </typeparam> /// <param name = "action"> </param> // <returns> </returns> public static MethodCallExpression GetMethodCall <T> (Expression <T> action) {var call = action. body as MethodCallExpression; return call ;}

(6). Get the type name.

/// <Summary> /// obtain the type name /// </summary> /// <typeparam name = "T"> </typeparam> /// <returns> </returns> public static string GetTypeName <T> () {return typeof (T ). name ;}

(7). Get the parameter value

/// <Summary> /// obtain the parameter value /// </summary> /// <param name = "methodCall"> </param> /// <returns> </returns> public static IEnumerable <Tuple <ParameterInfo, object> GetArgumentValues (MethodCallExpression methodCall) {var parameters = methodCall. method. getParameters (); if (! Parameters. any () yield break; for (var I = 0; I <parameters. length; I ++) {var arg = methodCall. arguments [I]; var ceValue = arg as ConstantExpression; if (ceValue! = Null) yield return new Tuple <ParameterInfo, object> (parameters [I], ceValue. value); else yield return new Tuple <ParameterInfo, object> (parameters [I], GetExpressionValue (arg ));}}

(8). Get the expression value

/// <Summary> /// obtain the expression value /// </summary> /// <param name = "expression"> </param> /// <returns> </returns> private static object GetExpressionValue (Expression expression) {var lambda = Expression. lambda <Func <object> (Expression. convert (expression, typeof (object); var func = lambda. compile (); return func ();}

The hierarchy of reflection classes is as follows:

System. reflection

System. Reflection. Assembly

System. Reflection. MemberInfo
System. Reflection. EventInfo
System. Reflection. FieldInfo
System. Reflection. MethodBase
System. Reflection. ConstructorInfo
System. Reflection. MethodInfo
System. Reflection. PropertyInfo
System. Type

 

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.