How to extend methods to a class not to its instances
Extending methods to any instance is really easy:
public static string LeaveJustNumbers(this string text)
{
return Regex.Replace(text, @"[\D]", "");
}
...
string JustNumbers = "A5gfb343j4".LeaveJustNumber(开发者_StackOverflow中文版);
But what if i want to extend methods to a sealed class like string, to work like:
string.Format("Hi:{0}","Fraga");
Is there any way to do it?
If you're talking about 'extending' static methods (or replacing existing ones), then as far as I know, no, you can't do it and I'm not sure why you'd want to.
The main point of extension methods is so that the calling style is that of an method call on the instance. It allows for more elegant syntax and method chaining, amongst other things. LINQ without extension methods would be horrendously painful, for example.
You have three options, one of which is extremely horrible:
Make a normal extension method that makes the call on the static method
public static string SomeExtensionMethod(this string name)
{
return string.Format("Hi:{0}", name);
}
Usage:
Console.WriteLine("Mr Smith".SomeExtensionMethod());
Create a static helper class and make the call using that
Console.WriteLine(MyHelperClass.SomeMethod("Mr Smith"));
And the evil one
Create a static helper class with the same name as the type you want to 'extend' (e.g. public class String) ... then duplicate the static target method's signature (Format) and watch everyone cry hot salty tears of confusion when they see a type named "string" that isn't from the "System" namespace and they have to smatter their .cs file with using String=MyCrazyHacks.String and/or explicit namespaces.
I'm not even sure if you could do this to "string" as it's an alias for System.String, so I've changed the example to use the name "String" instead.
namespace MyCrazyHacks
{
public static class String
{
public static System.String Format(
System.String str, params object[] zeParams)
{
// do bad, unspeakable things that confuses everyone
return System.String.Format(....);
}
}
}
Note: please don't do this because you will cause great suffering...
精彩评论