c# – 获取类型的默认PropertyDescriptors

我通过实现ICustomTypeDescriptor来自定义PropertyGrid中对象类型的显示方式.我允许用户创建自己的自定义属性,它们存储在单个字典的键和值中.我可以为这些值创建所有的PropertyDescriptors,并在属性网格中查看它们.但是,如果PropertyGrid是通过反射而不是覆盖ICustomTypeDescriptor.GetProperties方法,我还想显示所有属性,否则将显示.

现在我知道如何获取对象的类型,然后获取GetProperties(),但是这会返回PropertyInfo的数组,而不是ProperyDescriptor.那么如何将PropertyInfo对象的类型转换为PropertyDescriptor对象,以便包含在我的集合中,并使用自定义的PropertyDescriptors?

//gets the local intrinsic properties of the object
Type thisType = this.GetType();
PropertyInfo[] thisProps = thisType.GetProperties();

//this line obvIoUsly doesn't work because the propertydescriptor 
//collection needs an array of PropertyDescriptors not PropertyInfo
PropertyDescriptorCollection propCOl = 
    new PropertyDescriptorCollection(thisProps);

解决方法

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(thisType);

除此之外:这不包括您的ICustomTypeDescriptor自定义,但它将包括通过TypeDescriptionProvider进行的任何定制.

(编辑)
除了第二个 – 您还可以通过提供一个TypeConverter来调整PropertyGrid – 比ICustomTypeDescriptor或TypeDescriptionProvider更简单 – 例如:

[TypeConverter(typeof(FooConverter))]
class Foo { }

class FooConverter : ExpandableObjectConverter
{
    public override PropertyDescriptorCollection GetProperties(
       ITypeDescriptorContext context,object value,Attribute[] attributes)
    {
        // your code here,perhaps using base.GetPoperties(
        //    context,value,attributes);
    }
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...