Extension methods on a static class? [duplicate]

2019-04-04 15:17发布

Possible Duplicate:
Can I add extension methods to an existing static class?

I know i can do the below to extend a class. I have a static class i would like to extend. How might i do it? I would like to write ClassName.MyFunc()

static public class SomeName
{
    static public int HelperFunction(this SomeClass v)

3条回答
ら.Afraid
2楼-- · 2019-04-04 15:23

You can't have extension methods on static classes because extension methods are only applicable to instantiable types and static classes cannot be instantiated.

Check this code..

    public static bool IsEmail(this string email)
    {
        if (email != null)
        {
            return Regex.IsMatch(email, "EmailPattern");
        }

        return false;
    }

First parameter to IsEmail() is the extending type instance and not just the type itself. You can never have an instance of a static type.

查看更多
淡お忘
3楼-- · 2019-04-04 15:31

You might want to turn your static class into a singleton. Then there will only be one instance of the class. And you can use extension methods on it because it's an instance.

This is provided you have access to the source code of the class.

查看更多
倾城 Initia
4楼-- · 2019-04-04 15:42

You can't extend static classes in C#. Extension methods work by defining static methods that appear as instance methods on some type. You can't define an extension method that extends a static class.

查看更多
登录 后发表回答