如何在C#中重写String类中的函数

Jro*_*nny 5 string extension-methods overloading sealed c#-4.0

例如,我需要查看字符串是否包含子字符串,所以我只是这样做:

String helloworld = "Hello World";
if(helloworld.Contains("ello"){
    //do something
}
Run Code Online (Sandbox Code Playgroud)

但如果我有一系列的项目

String helloworld = "Hello World";
String items = { "He", "el", "lo" };
Run Code Online (Sandbox Code Playgroud)

我需要在String类中创建一个函数,如果数组中的任何一个项包含在字符串中,它将返回true.

我想为这个场景覆盖包含(IEnumerable)函数Contains(string),而不是在另一个类中创建一个函数.是否可以这样做,如果是这样,我们如何覆盖这个功能?非常感谢你.

所以这里是完整的解决方案(谢谢你们):

public static bool ContainsAny(this string thisString, params string[] str) {
    return str.Any(a => thisString.Contains(a));
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 17

您无法覆盖该函数,但您可以为此创建扩展方法:

public static class StringExtensions {
     public static bool ContainsAny(this string theString, IEnumerable<string> items)
     {
         // Add your logic
     }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以像调用字符串上的普通方法一样调用它,只要您引用程序集并包含命名空间:

String helloworld = "Hello World";
String[] items = new string[] { "He", "el", "lo" };

if (helloworld.ContainsAny(items)) { 
   // Do something
}
Run Code Online (Sandbox Code Playgroud)

(当然,你可以称之为"包含",就像标准的字符串方法一样,但我更愿意给它一个更明确的名字,所以很明显你正在检查...)