TargetException:Object与目标类型不匹配

时间:2014-02-14 12:50:42

标签: reflection reflection.emit

当我尝试这段代码时,我遇到了这个奇怪的错误:

class SomeClass
{
    public decimal ClientCode { get; set; }
    public DateTime Date { get; set; }

    public override int GetHashCode()
    {
        int sum = 0;
        foreach (var p in GetType().GetProperties())
        {
            var method = p.GetType().GetMethod("GetHashCode");
            var value = p.GetValue(this, null);
            sum += (int)(method.Invoke(value, null)); //  <-- HERE!
        }

        return sum;
    }
}

这有什么问题?我正在迭代属性,因为这个代码将被发出。

1 个答案:

答案 0 :(得分:1)

我必须从对象获取GetHashCode,而不是从PropertyType

获取
public class SomeClass
{
    public decimal ClientCode { get; set; }
    public DateTime Date { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public byte B { get; set; }

    public override int GetHashCode()
    {
        int sum = 0;
        foreach (var p in GetType().GetProperties())
        {
            var method = typeof(object).GetMethod("GetHashCode");
            var value = p.GetValue(this, null);
            if (value != null)
                sum += (int)(method.Invoke(value, null));
        }

        return sum;
    }
}