【发布时间】:2018-12-14 11:39:38
【问题描述】:
我想通过指定点分隔路径来更新任何公共属性中的值。
但是每当我调用我的方法时,我都会收到一条错误消息:
pi.SetValue(instance, value1, null);
错误信息:
对象与目标类型不匹配。
我的方法:
private void SetPathValue(object instance, string path, object value)
{
string[] pp = path.Split('.');
Type t = instance.GetType();
for (int i = 0; i < pp.Length; i++)
{
PropertyInfo pi = t.GetProperty(pp[i]);
if (pi == null)
{
throw new ArgumentException("Properties path is not correct");
}
else
{
instance = pi.GetValue(instance, null);
t = pi.PropertyType;
if (i == pp.Length - 1)//last
{
// Type targetType = IsNullableType(pi.PropertyType) ? Nullable.GetUnderlyingType(pi.PropertyType) : pi.PropertyType;
var value1 = Convert.ChangeType(value, instance.GetType());
pi.SetValue(instance, value1, null);//ERROR
}
}
}
}
private static bool IsNullableType(Type type)
{
return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}
【问题讨论】:
-
当你有一个嵌套属性时,为什么你认为
t.GetProperty对你的原始对象的类型起作用?因此,当instance是MyType类型并且具有PropType类型的属性MyProperty时,t将始终计算为MyType,并且t.GetProperty(pp[1])返回null,因为pp[1]是其中的一个属性PropType,不在MyType内。您需要一个仅评估当前级别的递归方法。 -
@HimBromBeere 他在循环中更新
t,它并不总是原始值。我仍然同意递归评估是一个更合适的解决方案。 -
顺便说一句:如果没有设置任何中间属性(null),你想做什么?
-
@BradleyUffner Aaah,我确实错过了 OPs 代码中的这一点。
-
我认为这最终会尝试将值设置为“太深一层”。
标签: c# reflection propertyinfo