【问题标题】:Setting a value of an object's child property problem设置对象的子属性值问题
【发布时间】:2010-11-25 11:21:54
【问题描述】:

我使用此代码获取对象的子属性,

PropertyDescriptorCollection childProperties = TypeDescriptor.GetProperties(theObject)[childNode.Name].GetChildProperties();

认为“theObject”变量是一个文本框,我尝试设置 TextBox.Font.Bold = true;

我将此代码用于主要属性,并且在我自定义主要属性时它可以工作。但是当我访问子属性时,

我收到一个错误,即“对象引用未设置为对象的实例。”。

foreach (PropertyDescriptor childProperty in childProperties)
        {
            foreach (XmlAttribute attribute in attributes)
            {
                if (childProperty.Name == attribute.Name)
                {

                    if (!childProperty.IsReadOnly)
                    {

                        object convertedPropertyValue = ConverterHelper.ConvertValueForProperty(attribute.Value, childProperty);

                        childProperty.SetValue(theObject, convertedPropertyValue); //exception throw here

                        break;
                    }
                }
            }
        }

【问题讨论】:

  • 你能粘贴完整的例外吗

标签: .net components


【解决方案1】:

您似乎将错误的对象传递给SetValue - 从表面上看,您似乎得到了以下内容:

<TextBox>
  <Font Bold="true"/>
</Textbox>

然后您获得文本框的Font 属性和字体的Bold 属性,然后您尝试将值true 分配给BoldBold 属性。显然这是行不通的。

可能是这样的:

PropertyDescriptor objProp = TypeDescriptor.GetProperties(theObject)[childNode.Name];
PropertyDescriptorCollection childProperties = objProp.GetChildProperties();

foreach (PropertyDescriptor childProperty in childProperties) {
    foreach (XmlAttribute attribute in attributes) {
        if (childProperty.Name == attribute.Name && !childProperty.IsReadOnly) {
            Object convertedPropertyValue = converterHelper.ConvertValueForProperty(attribute.Value, childProperty);
            childProperty.SetValue(objProp.getValue(theObject), convertedPropertyValue);
        }
    }
}

注意设置子对象属性的上下文是子对象而不是父对象。

【讨论】:

  • 我可以从 xml 中获取属性和值。那里没有问题,但现在我收到此错误:“对象与目标类型不匹配。”当 SetValue 方法时。
  • 我想我发现了我的错误,我认为 childObject 是Font 的实例,但事实并非如此。我已经重新编辑了答案,这次试试吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 2013-10-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多