.Net中提供了两种方式访问类型的元数据:System.Reflection命名空间中提供的反射API和TypeDescriptor类。
反射适用于所有类型的常规机制,它为类型返回的信息是不可扩展的,因为它不能再编译之后修改。
与此相反,TypeDescriptor是一种可扩展的组件,实现了IComponent接口。
TypeDescriptor有缓存功能,第一次反射,以后就自动缓存了。所以如果你自己懒得缓存反射结果,那么优先使用 TypeDescriptor

下面是一些TypeDescriptor的案例:

案例1:使用TypeDescriptor给类动态添加Attribute,只能通过TypeDescriptor获取Attribute(也可以给对象动态添加Attribute,使用AddAttributes的另一个重载)

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

案例2:获取属性成员

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);
}

案例3:泛型转换器

 public static class StringExtension
{
public static T Convert<T>(this string input)
{
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
return (T)converter.ConvertFromString(input);
}
return default(T);
}
catch (Exception)
{
return default(T);
}
} public static object Convert(this string input, Type type)
{
try
{
var converter = TypeDescriptor.GetConverter(type);
if (converter != null)
{
return converter.ConvertFromString(input);
}
return null;
}
catch (Exception)
{
return null;
}
} } ------------------------------------------------------- "111".Convert<double>();
"True".Convert<bool>();

最新文章

  1. cocoapods真机调试出现问题解决
  2. geotrellis使用(二十一)自动导入数据
  3. 安卓贴图源码---&gt;单点触控.多点触控.类似in/百度魔图
  4. CI(CodeIgniter)框架入门教程——第二课 初始MVC
  5. JAVA 构造方法之间的调用
  6. c++11 pod类型(了解)
  7. 51nod1495 中国好区间
  8. Leetcode237:Delete Node in a Linked List
  9. hihocoder #1223 : 不等式 水题
  10. Centos系统备份与恢复教程
  11. openStack 使用public key登陆
  12. [转载]Android利用convertView优化ListView性能
  13. IC卡
  14. waitpid 函数详解
  15. Debug程序的使用
  16. Node.js api接口和SQL数据库关联
  17. FastJson中JSONObject用法及常用方法总结
  18. 中标麒麟(linux)下Qt调用python
  19. grid - 它和flex布局有何区别?
  20. ansible-playbook 快速入门

热门文章

  1. Kafka为什么速度那么快?
  2. TypeError: Dense_net() takes 0 positional arguments but 1 was given
  3. contentType: &#39;application/json&#39; C#后台怎么处理
  4. Maven介绍及环境搭建
  5. Distributed and Parallel Computing
  6. HttpInvoker GET/POST方式
  7. python学习--大数据与科学计算第三方库简介
  8. 配置ssl使用了不受支持的协议。 ERR_SSL_VERSION_OR_CIPHER_MISMATCH
  9. C#工具类MySqlHelper,基于MySql.Data.MySqlClient封装
  10. JS 对象属性名排序