PropertyInfo 实例上的 SetValue 错误“对象与目标类型不匹配” C#
在以前的项目中的各个地方都使用了包含此代码的 Copy 方法(以处理具有相同命名属性但不从公共基类派生或实现公共接口的对象)。
新的工作地点,新的代码库 - 现在即使在非常简单的示例上,它也会在 SetValue 处失败,并显示“对象与目标类型不匹配”...上周它工作了...
public static void Copy(object fromObj, object toObj)
{
Type fromObjectType = fromObj.GetType();
Type toObjectType = toObj.GetType();
foreach (System.Reflection.PropertyInfo fromProperty in
fromObjectType.GetProperties())
{
if (fromProperty.CanRead)
{
string propertyName = fromProperty.Name;
Type propertyType = fromProperty.PropertyType;
System.Reflection.PropertyInfo toProperty =
toObjectType.GetProperty(propertyName);
Type toPropertyType = toProperty.PropertyType;
if (toProperty != null && toProperty.CanWrite)
{
object fromValue = fromProperty.GetValue(fromObj,null);
toProperty.SetValue(toProperty,fromValue,null);
}
}
}
}
private class test
{
private int val;
private string desc;
public int Val { get { return val; } set { val = value; } }
public string Desc { get { return desc; } set { desc = value; } }
}
private void TestIt()
{
test testo = new test();
testo.Val = 2;
testo.Desc = "TWO";
test g = new test();
Copy(testo,g);
}
希望有人能指出我在哪里愚蠢???
Been using a Copy method with this code in it in various places in previous projects (to deal with objects that have same named properties but do not derive from a common base class or implement a common interface).
New place of work, new codebase - now it's failing at the SetValue with "Object does not match target type" even on very simple examples... and it worked last week....
public static void Copy(object fromObj, object toObj)
{
Type fromObjectType = fromObj.GetType();
Type toObjectType = toObj.GetType();
foreach (System.Reflection.PropertyInfo fromProperty in
fromObjectType.GetProperties())
{
if (fromProperty.CanRead)
{
string propertyName = fromProperty.Name;
Type propertyType = fromProperty.PropertyType;
System.Reflection.PropertyInfo toProperty =
toObjectType.GetProperty(propertyName);
Type toPropertyType = toProperty.PropertyType;
if (toProperty != null && toProperty.CanWrite)
{
object fromValue = fromProperty.GetValue(fromObj,null);
toProperty.SetValue(toProperty,fromValue,null);
}
}
}
}
private class test
{
private int val;
private string desc;
public int Val { get { return val; } set { val = value; } }
public string Desc { get { return desc; } set { desc = value; } }
}
private void TestIt()
{
test testo = new test();
testo.Val = 2;
testo.Desc = "TWO";
test g = new test();
Copy(testo,g);
}
Hopefully someone can point out where I am being daft???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
应该
Should be
尝试:
您尝试传入属性 (
toProperty
) 作为目标对象,而不是toObj
。 有关信息,如果您要做很多这样的事情,也许可以考虑 HyperDescriptor,它可以大大减少反射成本。Try:
You are trying to pass in the property (
toProperty
) as the target object, instead oftoObj
. For info, if you are doing lots of this, maybe consider HyperDescriptor, which can vastly reduce the reflection cost.