开发者

C# Overloading operator== outside the class

开发者 https://www.devze.com 2023-04-03 20:53 出处:网络
I have the following scenario: public class SomeClass { // Have some other data members as well public int i ;

I have the following scenario:

    public class SomeClass { 
       // Have some other data members as well  
       public int i ; 
    } 

    public class TestClass { 

        public bool SomeFunction() { 
             SomeClass a = new SomeClass(); 
             SomeClass b = new SomeClass(); 
             if (a == b) // this is where I am getting compile error
               return true; 
             return false; 
         } 

        public static bool operator==(SomeClass a, SomeClass b) { 
             if (a.i == b.i)
               return true; 
             // compare some other members as well
             return false; 
        } 
    } 

Is this possible to achieve 开发者_运维知识库in C#?

Thanks for the help!


No, it's not possible to override an operator from a class that is not involved in the operation.


You can make a class that implements IEualityComparer<SomeClass>, which can be used instead of the standard comparison in some cases, for example in a dictionary:

var x = new Dictionary<SomeClass, string>(new SomeClassEqualityComparer());

If you just want to use the comparison in your own class, you could make it a regular static method instead of overriding an operator:

public static bool SomeClassEqual(SomeClass a, SomeClass b) { 
  if (a.i == b.i) {
    return true;
  }
  // compare some other members as well
  return false; 
}

Usage:

if (SomeClassEqual(a, b))


To begin with, you can't use return true; on a void method.

Second, overriding operators should be applied to the host class. In your case, inside SomeClass rather than inside TestClass.

Third, when you implement == overriding operator, you should also implement != .

Here is your code, revised and working:

public class SomeClass
{
    // Have some other data members as well  
    public int i;

    public static bool operator ==(SomeClass a, SomeClass b)
    {
        if (a.i == b.i)
            return true;
        // compare some other members as well
        return false;
    }

    public static bool operator !=(SomeClass a, SomeClass b)
    {
        return !(a == b);
    }
}

public class TestClass
{

    public bool SomeFunction()
    {
        SomeClass a = new SomeClass();
        SomeClass b = new SomeClass();
        if (a == b) // this is where I am getting compile error
            return true;

        return false;
    }
}
0

精彩评论

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