.Net反射-TypeDescriptor
2024-08-25 05:54:37
.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>();
最新文章
- cocoapods真机调试出现问题解决
- geotrellis使用(二十一)自动导入数据
- 安卓贴图源码--->;单点触控.多点触控.类似in/百度魔图
- CI(CodeIgniter)框架入门教程——第二课 初始MVC
- JAVA 构造方法之间的调用
- c++11 pod类型(了解)
- 51nod1495 中国好区间
- Leetcode237:Delete Node in a Linked List
- hihocoder #1223 : 不等式 水题
- Centos系统备份与恢复教程
- openStack 使用public key登陆
- [转载]Android利用convertView优化ListView性能
- IC卡
- waitpid 函数详解
- Debug程序的使用
- Node.js api接口和SQL数据库关联
- FastJson中JSONObject用法及常用方法总结
- 中标麒麟(linux)下Qt调用python
- grid - 它和flex布局有何区别?
- ansible-playbook 快速入门
热门文章
- Kafka为什么速度那么快?
- TypeError: Dense_net() takes 0 positional arguments but 1 was given
- contentType: &#39;application/json&#39; C#后台怎么处理
- Maven介绍及环境搭建
- Distributed and Parallel Computing
- HttpInvoker GET/POST方式
- python学习--大数据与科学计算第三方库简介
- 配置ssl使用了不受支持的协议。 ERR_SSL_VERSION_OR_CIPHER_MISMATCH
- C#工具类MySqlHelper,基于MySql.Data.MySqlClient封装
- JS 对象属性名排序