PropertyInfo 实例上的 SetValue 错误“对象与目标类型不匹配”c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/755646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SetValue on PropertyInfo instance error "Object does not match target type" c#
提问by kpollock
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).
在以前的项目中的不同地方使用了带有此代码的 Copy 方法(以处理具有相同命名属性但不从公共基类派生或实现公共接口的对象)。
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....
新的工作场所,新的代码库 - 现在即使在非常简单的例子中,它在 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);
}
Hopefully someone can point out where I am being daft???
希望有人能指出我愚蠢的地方???
采纳答案by Marc Gravell
Try:
尝试:
toProperty.SetValue(toObj,fromValue,null);
You are trying to pass in the property (toProperty
) as the target object, instead of toObj
. For info, if you are doing lots of this, maybe consider HyperDescriptor, which can vastly reduce the reflection cost.
您正在尝试将属性 ( toProperty
) 作为目标对象而不是toObj
. 有关信息,如果你做了很多这样的事情,也许可以考虑HyperDescriptor,它可以大大降低反射成本。
回答by Peter Lillevold
Should be
应该
toProperty.SetValue(toObj,fromValue,null);