加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取类型的默认PropertyDescriptors

发布时间:2020-12-15 03:58:54 所属栏目:百科 来源:网络整理
导读:我通过实现ICustomTypeDescriptor来自定义PropertyGrid中对象类型的显示方式.我允许用户创建自己的自定义属性,它们存储在单个字典的键和值中.我可以为这些值创建所有的PropertyDescriptors,并在属性网格中查看它们.但是,如果PropertyGrid是通过反射而不是覆
我通过实现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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读