c# - 可以在 .net 中扩展 String 类

标签 c# .net

如何覆盖或扩展 .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/

相关文章:

c# - 如何让线程休眠直到收到异步函数的回调?

c# - 自定义 EventHandler 与 EventHandler<EventArgs>

c# - 为移动浏览器设计网页的技巧?

c# - 使用 itextsharp 在 C# 中提取阿拉伯语文本

.net - 最快的搜索技术/方法是什么? (在文件搜索的上下文中)

c# - ScrollViewer.ScrollToBottom 未完全滚动

.net - Asp net 验证错误消息从不显示

c# - MongoDB C# GetById 使用 Find

c# - System.NullReferenceException 未在第一个 Try/Catch block 中捕获

c# - 在 Entity Framework ADO.NET 实体数据模型中导入 SQL Server 函数时出错