【.NET反射】TypeDescriptor

概述

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

TypeDescriptor案例

动态添加Attribute

//为Person类型添加DescriptAttribute
TypeDescriptor.AddAttributes(typeof(Person), new DescriptionAttribute("描述内容"));
//获取Person类型上的Attributes
var attrs = TypeDescriptor.GetAttributes(typeof(Person));
//获取Person对象上的Attributes
attrs = TypeDescriptor.GetAttributes(new Person());
//获取DescriptionAttribute
var descriptionAttr = (DescriptionAttribute)attrs[typeof(DescriptionAttribute)];

获取属性

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>();
posted @   .Neterr  阅读(187)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2020-04-12 Polly+AspectCore实现熔断降级

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示