我想创建一个扩展方法,该方法将通过其键返回枚举值。用法将是
LifeCycle.GetLifeCycle(1)
或 LifeCycle.GetLifeCycleByValue("")
这是我的想法-假设我有以下枚举:
public enum LifeCycle
{
Pending = 0,
Approved = 1,
Rejected = 2,
}
我为 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];
}
}
至今
LifeCycle.GetLifeCycle(1)
不编译。
这甚至可能吗?