How to override functions from String class in C#

拜拜、爱过 提交于 2019-12-05 10:43:57

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...)

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!