extension method to extend static class [duplicate]
I am wondering if I can use extension method or other techniques to extend static class like
System.Net.Mime.MediaTypeNames.Image
, it has fewer type than I need.
No, extension methods can only be used to add instance methods, not static methods (or even properties). Extension methods are really just syntactic sugar around static methods. For instance, when you use an extension method such as Count():
var list = GetList();
var size = list.Count();
This is actually compiled to:
var list = GetList();
var size = Enumerable.Count(list);
You can't add additional static methods to an existing class using extension methods.
No, this is not yet possible in C#, though hopefully it will become so at some point. And you can't subclass a static class and add new methods that way, since static classes must derive from object
. One thing you can do though, which produces a pretty similar effect in your code, is simply declare another static class that you will use instead when you want your extension methods. For example:
public static class MessageBox2
{
public static DialogResult ShowError(string Caption, string Message, params object[] OptionalFormatArgs)
{
return MessageBox.Show(string.Format(Message, OptionalFormatArgs), Caption, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Since the original class is static, by definition the "extension" method doesn't need to receive an instance as a this
parameter, and can simply use static methods of the original class.
精彩评论