C# 在类外重载运算符==

标签 c# operator-overloading overloading operator-keyword

我有以下场景:

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

这可以用 C# 实现吗?

感谢您的帮助!

最佳答案

不,不可能从不参与操作的类中覆盖操作符。


您可以创建一个实现 IEualityComparer<SomeClass> 的类,在某些情况下可以用来代替标准比较,例如在字典中:

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

如果您只想在自己的类中使用比较,可以将其设为常规静态方法而不是覆盖运算符:

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

用法:

if (SomeClassEqual(a, b))

关于C# 在类外重载运算符==,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376674/

相关文章:

c# - Elasticsearch Nest 6.5.1。我如何将原始请求发送到Elasticsearch

c# - 将按钮列添加到数据表

C++ 模板重载

c# - 结合泛型方法和重载

java - 方法重载中奇怪的 Java null 行为

c# - MVC 4 Entity Framework 一个特定的列不更新

C++加法重载歧义

c++ - 为什么 Visual C++ 编译器会在这里调用错误的重载?

java - 方法重载和泛型

c# - 添加了C#音效