【问题标题】:TargetException: Object does not match target typeTargetException:对象与目标类型不匹配
【发布时间】:2014-02-14 12:50:42
【问题描述】:

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

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;
    }
}

这有什么问题?我正在遍历属性,因为将发出此代码。

【问题讨论】:

    标签: reflection reflection.emit


    【解决方案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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 2011-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-04
      相关资源
      最近更新 更多