Unexpected behavior in c# generic method on .Equals

前端 未结 3 1746
孤独总比滥情好
孤独总比滥情好 2021-02-13 09:04

Why does the Equals method return a different result from within the generic method? I think that there\'s some automatic boxing here that I don\'t understand.

Here\'s a

3条回答
  •  一整个雨季
    2021-02-13 10:03

    TimeZoneInfo does not override the Object Equals method, so it calls the default Object Equals, which apparently does not work as expected. I would consider this a bug in TimeZoneInfo. This should work:

    private static Boolean Compare(T x, T y)
            where T: IEquatable
    {
        if (x != null)
        {
            return x.Equals(y);
        }
        return false;
    }
    

    The above will cause it to call Equals, which is the method you were calling above (it implicitly preferred the generic call because it was more specific to the parameter type than the Object Equals; inside the generic method, however, it had no way to be sure that such a generic Equals existed, since there was no constraint guaranteeing this).

提交回复
热议问题