【问题标题】:Object does not match target type Exception in SetValue对象与 SetValue 中的目标类型不匹配异常
【发布时间】:2016-09-06 20:41:32
【问题描述】:
//try to set this property .

 public List<USER_ROLE> list {get;set;}

var result = new List<USER_ROLE>() { new USER_ROLE()
                              { userid = 0,role_id = 1,role_cde = "00001"
                               }};
    //Get property with name of property.

object obj = Activator.CreateInstance(property.PropertyType);
var getva = property.GetValue(obj,null);// Object does not match target type


property.PropertyType.GetMethod("Add").Invoke(obj,new object[] { result });
if (obj.GetType() == property.PropertyType)
{
property.SetValue(obj, property, null);// object does not match target type.
}

运行时执行:对象与目标类型不匹配。我不明白目标类型,请告诉我哪里错了?

【问题讨论】:

  • PropertyType 是属性的返回类型,而obj 应该是包含该属性的类的实例。您可能想使用property.DeclaringType
  • 声明一个属性并在同一范围内分配值的事实似乎有点奇怪。这是你的文字代码吗?
  • 你说的怪人是什么意思。?我正在尝试制作将 VM_propterties 转换为模型属性的通用代码。你有更好的解决方案吗?
  • @FarhatUllah by bizzare,我的意思是您发布的代码实际上不会编译

标签: c# asp.net asp.net-mvc generics reflection


【解决方案1】:

查看the documentation 后,似乎认为您的第一个参数是您的原始对象,而您的第二个参数是您要设置属性的值。

您似乎想将该属性设置为obj,在这种情况下,您会这样做

property.SetValue(/*instance of whatever class has the property*/, obj, null);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多