.Net反射-TypeDescriptor

.Net provides two ways to access the type of the metadata: System.Reflection TypeDescriptor class name space and the Reflection API provided.
Reflection applies to all types of conventional mechanisms, it returns the type of information is not extensible because it can not be modified after compilation.
In contrast, a TypeDescriptor is an extensible components, implements IComponent interface.
There TypeDescriptor cache function, the first reflection, after automatically cached. So if you bother to cache the result of reflection, then the priority use TypeDescriptor

 

The following are some cases where the TypeDescriptor:

Case 1: dynamically added to the class using TypeDescriptor Attribute, Attribute can only be obtained through the TypeDescriptor (can also be dynamically added to the Attribute object, use the other overload AddAttributes)

TypeDescriptor.AddAttributes(typeof(targetObject), new simpleAttribute(new targetObject()));
AttributeCollection collection = TypeDescriptor.GetAttributes(typeof(targetObject));
simpleAttribute attr = ((simpleAttribute)collection[typeof(simpleAttribute)]);

Case 2: Get attribute member

var defaults = new { controller = "Home", action = "Index", id = UrlParameter.Optional };
 
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(defaults);
            foreach (PropertyDescriptor prop in props)
            {
                object val = prop.GetValue(defaults);
                Console.WriteLine("name:{0}, value:{1}", prop.Name, val);
            }

Case 3: generic converter

 1 public static class StringExtension
 2     {
 3         public static T Convert<T>(this string input)
 4         {
 5             try
 6             {
 7                 var converter = TypeDescriptor.GetConverter(typeof(T));
 8                 if (converter != null)
 9                 {
10                     return (T)converter.ConvertFromString(input);
11                 }
12                 return default(T);
13             }
14             catch (Exception)
15             {
16                 return default(T);
17             }
18         }
19 
20         public static object Convert(this string input, Type type)
21         {
22             try
23             {
24                 var converter = TypeDescriptor.GetConverter(type);
25                 if (converter != null)
26                 {
27                     return converter.ConvertFromString(input);
28                 }
29                 return null;
30             }
31             catch (Exception)
32             {
33                 return null;
34             }
35         }
36 
37     }

-------------------------------------------------------

"111".Convert<double>();
"True".Convert<bool>();

 

Guess you like

Origin www.cnblogs.com/fanfan-90/p/11961228.html