问题
For example, I need to see if a string contains a substring, so I just do:
String helloworld = "Hello World";
if(helloworld.Contains("ello"){
//do something
}
but if I have an array of items
String helloworld = "Hello World";
String items = { "He", "el", "lo" };
I needed to create a function inside the String class that would return true if either of the items inside the array is contained in the string, for example.
I would like to override the function Contains(string) with Contains(IEnumerable) for this scenario, instead of creating a function in another class. Is it possible to do this, and if so, how can we override the function? Thank you very much.
So here goes the complete solution (thanks guys):
public static bool ContainsAny(this string thisString, params string[] str) {
return str.Any(a => thisString.Contains(a));
}
回答1:
You can't override the function, but you can make an extension method for this:
public static class StringExtensions {
public static bool ContainsAny(this string theString, IEnumerable<string> items)
{
// Add your logic
}
}
You'd then call this just like a normal method on a string, provided you reference the assembly and include the namespace:
String helloworld = "Hello World";
String[] items = new string[] { "He", "el", "lo" };
if (helloworld.ContainsAny(items)) {
// Do something
}
(Granted, you could call this "Contains", like the standard string method, but I would prefer to give it a more explicit name so it's obvious what you're checking...)
回答2:
Why not keep things simple and use the Any extension method?
string helloworld = "Hello World";
string[] items = { "He", "el", "lo" };
if (items.Any(item => helloworld.Contains(item)))
{
// do something
}
来源:https://stackoverflow.com/questions/3137338/how-to-override-functions-from-string-class-in-c-sharp