C# String Operator Overloading

前端 未结 7 2000
自闭症患者
自闭症患者 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:39

    You cannot directly overload the >= and <= operator, but you can achieve the same result by overload the > and the == separately.

    Your code seems correct to me, except the fact that you miss the overloading for ==.

    Seems I was wrong, however, you can always fall back to reflection. I think if you do some digging and hacking, you can make it work with reflection to extend the class since reflection allows to add functions or swap function bodies at runtime.

    Whether it is advisable and good practice, I doubt it. There is a reason why the class is sealed. Doing the thing I mentioned may result in undefined behavior in some circumstances due to some assumptions the .net framework makes on strings. Chances are big that the string class will collapse internally.

提交回复
热议问题