سؤال

I'm getting this wierd error when I try this code:

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

What's wrong with that? I'm iterating through properties cause this code will be emitted.

هل كانت مفيدة؟

المحلول

I must get GetHashCode from object, not from 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;
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top