6

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

String helloworld = "Hello World";
if(helloworld.Contains("ello"){
    //do something
}

但如果我有一系列项目

String helloworld = "Hello World";
String items = { "He", "el", "lo" };

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

对于这种情况,我想用 Contains(IEnumerable) 覆盖函数 Contains(string),而不是在另一个类中创建函数。是否可以这样做,如果可以,我们如何覆盖该功能?非常感谢你。

所以这是完整的解决方案(谢谢大家):

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

2 回答 2

17

您不能覆盖该功能,但您可以为此创建一个扩展方法

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

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

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

if (helloworld.ContainsAny(items)) { 
   // Do something
}

(当然,您可以将其称为“包含”,就像标准的字符串方法一样,但我更愿意给它一个更明确的名称,以便您检查的内容很明显......)

于 2010-06-29T01:54:53.400 回答
4

为什么不保持简单并使用Any扩展方法

string helloworld = "Hello World";
string[] items = { "He", "el", "lo" };
if (items.Any(item => helloworld.Contains(item)))
{
    // do something
}
于 2010-06-29T01:57:03.003 回答