开发者

extension method to extend static class [duplicate]

This question already has answers here: Can I add extension methods to an existing static class? (18 answers) 开发者_开发知识库 Closed 8 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜