简体   繁体   中英

Possible to extend the String class in .net

How to override or extend .net main classes. for example

public class String
{
    public boolean contains(string str,boolean IgnoreCase){...}
    public string replace(string str,string str2,boolean IgnoreCase){...}
}

after

string aa="this is a Sample";
if(aa.contains("sample",false))
{...}

is it possible?

The String class is sealed so you can't inherit from it. Extension methods are your best bet. They have the same feel as instance methods without the cost of inheritance.

public static class Extensions {
  public static bool contains(this string source, bool ignoreCase) {... }
}

void Example {
  string str = "aoeeuAOEU";
  if ( str.contains("a", true) ) { ... }
}

You will need to be using VS 2008 in order to use extension methods.

The String class is sealed, so you cannot extend it. If you want to add features you can either use extension methods or wrap it in a class of your own and provide whatever additional features you need.

In general, you should try to see if there is another method that will answer your needs in a similar manner. For your example, Contains is actually a wrapper method to IndexOf , return true if the returned value is greater than 0, otherwise false . As it happens, the IndexOf method has a number of overloads, one of which is IndexOf( string, StringComparison ): Int32 , which can be specified to honor or ignore case.

See String.IndexOf Method (String, StringComparison) (System) for more information, although the example is a little weird.

See StringComparison Enumeration (System) for the different options available when using the StringComparison enumeration.

You can also use an adapter pattern to add additional functionality. You can do operator overloading to make it feel like the built in string. Of course this won't be automatic for existing uses of "string" but neither would your solution of directly inheriting from it, if it were possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM