C#字符串运算符重载 [英] C# String Operator Overloading
问题描述
配合儿真好 -
什么是(不包括它是否是可取的说法)超载字符串运算符<,>,<的正确方法; ?=和> =
What is the right way (excluding the argument of whether it is advisable) to overload the string operators <, >, <= and >= ?
我已经试过了五种方式周日,我去各种错误 - 我最好的射门被宣布的分部类,并从那里超载,但它不会出于某种原因。
I've tried it five ways to Sunday and I get various errors - my best shot was declaring a partial class and overloading from there, but it won't work for some reason.
namespace System
{
public partial class String
{
public static Boolean operator <(String a, String b)
{
return a.CompareTo(b) < 0;
}
public static Boolean operator >(String a, String b)
{
return a.CompareTo(b) > 0;
}
}
}
}
推荐答案
字符串是一个密封类。你不能继承它,并没有原始源字符串,您不能编译一个分部类的吧。即使你在源上得到了你的手(它通过反射或者通过Visual Studio的符号下载是可能的),你仍然有问题,因为它在运行中的头等公民。
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.
你真的需要<和>作为字符串操作?如果是这样的...为什么不直接使用扩展方法的<? / p>
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
这篇关于C#字符串运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!