开发者

Static operator == not detect overrated method

I have base class Class1 and a derived class2. I create two instances of class2 but defined as class1. My problem is I can't do a generic compare between this objects. Here are an example:

    public class Class1
    {
        public int Property1 = 0;
    }

    public class Class2 :  Class1
    {
        public int Property2 = 0;

        public static bool operator ==(Class2 c1, Class2 c2)
        {
            return c1.Property2 == c2.Property2;
        }

        public static bool operator !=(Class2 c1, Class2 c2)
        {
            return c1.Property2 != c2.Property2;
        }
    }

    public class Class3 :  Class1
    {
        public int Property3 = 0;
    }

    static void Main(string[] args)
    {
        Class1 obj1 = new Class2();
        Class1 obj2 = new Class2();

        if (obj1 == obj2)
        {
            Console.WriteLine("Yes !!! The two objects are equal!");
        }
        els开发者_开发问答e
        {
            Console.WriteLine("The two objects are not equal.");
        }
    }

if I change the line:

if (obj1 == obj2)

for:

if ((Class2)obj1 == (Class2)obj2)

all is right, but if obj1 and obj2 are Class3 I get error

How can I resolve it ?

Thank you

Crandel


Add your operator overloads to all the classes, in your example add it to Class1 as well to get it to work


In my opinion it is a bad idea to overload the == and != operators at all, since there default semantic with reference types is to compare references rather than values. I'd rather override bool Equals(System.Object) and int GetHashCode() and use Equals for value comparison - IMHO makes the code more readable by virtue of reducing ambiguity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜