微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐