How can I create extension methods with static return type?

我的未来我决定 提交于 2019-12-02 16:11:27

问题


I was trying to write a simple extension method for Color static class which return Black and White equivalent of that color.
The problem is that extention methods can't return Static types...
So, how can I do this?! please help me.


回答1:


The problem is that NO method can return a static type. Static classes are stateless (or have only static state), and thus have only one "instance" that is globally accessible from any code referencing the namespace.

You can return a Color; the Color class itself, though it has static members, is not static, and so many instances of Colors can exist. You can also apply an extension method to a Color. If you do this, then you can call an extension method on one of the static members of the non-static Color struct:

public static class MyColorsExtensions
{

   public static Color ToGreyScale(this Color theColor) { ... }

}

...

var greyFromBlue = Color.Blue.ToGreyScale();



回答2:


If you're referring to System.Drawing.Color - it's not a static class ... it's a struct. You should be able to return an instance of it from a method. It just so happens that the Color structure includes static members to represent specific colors - like: Color.Black and Color.White.

If you're not referring to that type, then please post a short sample of the code that fails.




回答3:


It's hard to understand what you are trying to say, but if you are trying to create a extension method for a static class, that is impossible because extension methods are for class instances.




回答4:


Is this what you're looking for? This is an extension method returning a static color struct.

public static class ColorExtensions
{
    private static Color MYCOLOR = Color.Black;
    public static Color BlackAndWhiteEquivalent(this Color obj)
    {
        // stubbed in - replace with logic for find actual
        // equivalent color given what obj is
        return MYCOLOR;
    }
}

and the test

    [Test]
    public void FindBlackAndWhiteColorEquivalent()
    {
        Color equivalentColor = Color.Black.BlackAndWhiteEquivalent();
    }



回答5:


try this

public static class Colores
{
public static Color Rojo = Color.FromArgb(0xE51600);
public static Color Azul = Color.FromArgb(0x004183);
public static Color Verde = Color.FromArgb(0x00865A);
public static Color Plata = Color.FromArgb(0xC4C5C7);
public static Color Gris = Color.FromArgb(0x58585A);
public static Color Cafe = Color.FromArgb(0x632600);
public static Color Negro = Color.Black;
}


来源:https://stackoverflow.com/questions/3755941/how-can-i-create-extension-methods-with-static-return-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!