.net 设置对象的值';儿童财产问题
我使用此代码获取对象的子属性 PropertyDescriptorCollection childProperties=TypeDescriptor.GetProperties(对象)[childNode.Name].GetChildProperties() 假设“theObject”变量是一个TextBox,我尝试设置TextBox.Font.Bold=true 我将此代码用于主属性,当我为主属性进行自定义时,它会起作用。但当我访问子属性时 我得到一个错误,即“对象引用未设置为对象的实例”.net 设置对象的值';儿童财产问题,.net,components,.net,Components,我使用此代码获取对象的子属性 PropertyDescriptorCollection childProperties=TypeDescriptor.GetProperties(对象)[childNode.Name].GetChildProperties() 假设“theObject”变量是一个TextBox,我尝试设置TextBox.Font.Bold=true 我将此代码用于主属性,当我为主属性进行自定义时,它会起作用。但当我访问子属性时 我得到一个错误,即“对象引用未设置为对象的实例” 看
看起来您将错误的对象传递给了
SetValue
——从表面上看,您得到了如下结果:
<TextBox>
<Font Bold="true"/>
</Textbox>
请注意,设置子对象属性的上下文是子对象,而不是父对象。您可以粘贴完整的异常吗?请从xml获取属性和值。这里没有问题,但现在我得到了这个错误:“对象与目标类型不匹配。”当使用SetValue方法时。我想我发现了错误,我假设childObject是
Font
的实例,但它不是。我重新编辑了答案,这次试试看。
<TextBox>
<Font Bold="true"/>
</Textbox>
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);
}
}
}