如何在枚举上创建扩展方法(c#)

Bic*_*ick 2 c# extension-methods enums

我想创建一个扩展方法,它将通过其键返回枚举值.用法将是

LifeCycle.GetLifeCycle(1) 
Run Code Online (Sandbox Code Playgroud)

或LifeCycle.GetLifeCycleByValue("")

这就是我的想法 - 假设我有以下枚举:

public enum LifeCycle
{
    Pending = 0,
    Approved = 1,
    Rejected = 2,
}
Run Code Online (Sandbox Code Playgroud)

我为getByint案例编写了以下扩展名

public static class EnumerationExtensions
{
    private static Dictionary<int, LifeCycle> _lifeCycleMap = Enum.GetValues(typeof(LifeCycle)).Cast<int>().ToDictionary(Key => Key, value => ((LifeCycle)value));

    public static LifeCycle GetLifeCycle(this LifeCycle lifeCycle, int lifeCycleKey)
    {
        return _lifeCycleMap[lifeCycleKey];
    }
}
Run Code Online (Sandbox Code Playgroud)

至今

 LifeCycle.GetLifeCycle(1) 
Run Code Online (Sandbox Code Playgroud)

doenst编译.

这甚至可能吗?

Ser*_*rvy 7

没有静态扩展方法,这是你想要做的.您只能创建在类型实例中起作用的扩展方法,而不是类型本身.


Tim*_*ter 5

LifeCycle 类型不是该枚举的实例.

所以这将编译:

LifeCycle.Pending.GetLifeCycle(1);
Run Code Online (Sandbox Code Playgroud)

但是这个扩展无论如何都是毫无意义的,因为你可以int直接得到它的值:

LifeCycle approved = (LifeCycle) 1;
Run Code Online (Sandbox Code Playgroud)