简体   繁体   中英

The “is” keyword and the override of Equals method

The documentation for the keyword "is" states that:

The is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered.

What does it mean in practice? Is it wrong to use it to check if a struct is a certain type? For example,

public struct Point2D
{
    public int X;
    public int Y;

    ...

    public override bool Equals(Object value)
    {
        if (value != null && value is Point2D)   // or if (value != null && GetType() == value.GetType())
        {
            Point2D right = (Point2D)value;
            return (X == right.X && Y == right.Y);
        }
        else return false;
    }

    ...
}

Checking whether a struct is a certain type is fine. The documentation means that user-defined explicit and implicit conversion operators are not evaluated when considering whether the given object is of the specified type, even if there is a user-defined operator that can convert it to said type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM