【问题标题】:PropertyDescriptorCollection - Object does not match target typePropertyDescriptorCollection - 对象与目标类型不匹配
【发布时间】:2016-04-05 13:31:58
【问题描述】:

我有一个带有 class1 类型对象的 SelectedObject 的 PropertyGrid。

我正在为class1 对象实现ICustomTypeDescriptor 接口,并且我从另一个对象class2 获得PropertyDescriptorCollection,并且需要在PropertyGrid 中显示class2 PropertyDescriptors 以及class1PropertyDescriptors

我在 class2 PropertyDescriptors 的 PropertyGrid 中显示以下错误:

对象与目标类型不匹配。

这是我在没有class2 PropertyDescriptors 的情况下工作的代码:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
    var propertyDescriptors = new List<PropertyDescriptor>();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(propertyDescriptorCollection[i]);
    }
    return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}

这是我正在处理的代码:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
    var propertyDescriptors = new List<PropertyDescriptor>();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(propertyDescriptorCollection[i]);
    }
    var class2PropertyDescriptorCollection = TypeDescriptor.GetProperties(class2);
    for (int i = 0; i < class2PropertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(class2PropertyDescriptorCollection[i]);
    }
    return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}

当来自class1PropertyDescriptors 显示在PropertyGrid 中时,如何显示来自class2PropertyDescriptors

【问题讨论】:

    标签: c# propertydescriptor icustomtypedescriptor


    【解决方案1】:

    您已将 propertyDescriptorCollection 声明为 PropertyDescriptorCollection 类型,但已将 var 用于 class2PropertyDescriptorCollection。如果您尝试以下方法会怎样:

    public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
        var propertyDescriptors = new List<PropertyDescriptor>();
        for (int i = 0; i < propertyDescriptorCollection.Count; i++)
        {
            propertyDescriptors.Add(propertyDescriptorCollection[i]);
        }
        PropertyDescriptorCollection class2PropertyDescriptorCollection = TypeDescriptor.GetProperties(class2);
        for (int i = 0; i < class2PropertyDescriptorCollection.Count; i++)
        {
            propertyDescriptors.Add(class2PropertyDescriptorCollection[i]);
        }
        return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      相关资源
      最近更新 更多