如何覆盖或扩展 .net 主类。例如
public class String
{
public boolean contains(string str,boolean IgnoreCase){...}
public string replace(string str,string str2,boolean IgnoreCase){...}
}
之后
string aa="this is a Sample";
if(aa.contains("sample",false))
{...}
这可能吗?
最佳答案
String 类是密封的,因此您不能继承它。扩展方法是您最好的选择。它们与没有继承成本的实例方法具有相同的感觉。
public static class Extensions {
public static bool contains(this string source, bool ignoreCase) {... }
}
void Example {
string str = "aoeeuAOEU";
if ( str.contains("a", true) ) { ... }
}
您需要使用 VS 2008 才能使用扩展方法。
关于c# - 可以在 .net 中扩展 String 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/525797/