C# String Operator Overloading

前端 未结 7 2017
自闭症患者
自闭症患者 2020-12-19 04:02

G\'Day Mates -

What is the right way (excluding the argument of whether it is advisable) to overload the string operators <, >, <= and >= ?

I\'ve trie

7条回答
  •  离开以前
    2020-12-19 04:36

    String is a sealed class. You cannot inherit from it, and without the original source for String, you cannot compile a partial class of it. Even if you got your hands on the source (it's possible via Reflector or via Visual Studio symbol download) you'd still have problems, since it's a first class citizen in the runtime.

    Do you really need < and > as operators on string? If so... why not just use extension methods?

    public static bool IsLessThan(this string a, string b) 
    { 
        return a.CompareTo(b) < 0; 
    } 
    
    public static bool IsGreaterThan(this string a, string b) 
    { 
        return a.CompareTo(b) > 0; 
    }
    
    
    // elsewhere...
    foo.IsLessThan(bar); // equivalent to foo < bar
    

提交回复
热议问题