2016-02-28 59 views
0

我記得關於一個接口的一些信息,如果它被實現的話,它會自動處理所有的比較運算符,所以沒有必要單獨實現每一個。有人記得這樣的事嗎?比較運算符重載一個尺寸適合所有

+0

見http://stackoverflow.com/a/43721867/5976576 – MotKohn

回答

1

恕我直言,沒有任何開箱即用的.NET可以做到這一點。 C#中的運算符被定義爲靜態方法,因此它們不能像IEnumerable(通過擴展方法)那樣共享。另外,EqualsGetHashCode方法必須明確重載(當您提供==!=運算符時),則不能使用擴展方法或任何其他語言機制在許多未分析的類中共享它們。

關閉你可能要做的事情是創建自定義基類,它將實現IComparable<>並覆蓋EqualsGetHashCode,並定義一組自定義運算符。

public class Base { 
    public static bool operator >(Base l, Base r) { 
     return true;  
    } 

    public static bool operator <(Base l, Base r) { 
     return false; 
    } 
} 

public class Derived : Base { } 
public class Derived2 : Base { } 

,然後使用:

Derived a = new Derived(), b = new Derived(); 
    bool g = (a > b); 


    Derived2 a2 = new Derived2(); 
    bool g2 = (a2 > b); 

但只會工作,爲密切相關的種...

+0

感謝,我忘了最後一個想法。 – MotKohn