简体   繁体   中英

How can I add static Extention method to a existing class in C#

for example, I can to use Color (the building class like that)

Color c = Color.GreenSmile();

this is my extension method, But I don't want to use an Instance. It is possible?

   public static Color GreenSmile(this Color color)
        {
           return Color.FromArgb(83, 255, 26);
        }

No, you can't omit the Color instance because an extension method needs an instance of the type it extends as first argument and the this keyword.

I want a static method, to use the name of the class.

You could create a new class Color in it's own namespace, although that could cause confusion.

namespace Drawing.Utilities
{
    internal class Color
    {
        public static System.Drawing.Color GreenSmile()
        {
            return System.Drawing.Color.FromArgb(83, 255, 26);
        }
    }
}

Now you can use this method as it was a System.Drawing.Color method:

var greenSmile = Color.GreenSmile(); // add using Drawing.Utilities;

But as mentioned above this can cause confusion, espcially because the method returns a different Color -type than itself. So it 's certainly better to use a different name for this class( ColorUtility ).

An extension-method is nothing but a static method that expects an instance of your class . However in your case you don´t seem to use the provided instance at all, so you can simply omit it from the method-signature and turn it into a normal static method:

public static Color GreenSmile()
{
    return Color.FromArgb(83, 255, 26);
}

Now you can call it like this:

Color c = MyClass.GreenSmile();

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