2013-02-12 289 views
0

我想將擴展方法添加到枚舉類型,但下面的代碼失敗。編譯器給出的錯誤行StoreType.GetAllItems如何將擴展方法添加到枚舉類型?擴展和枚舉類型

namespace ConsoleApplication1 
{ 

    public static class EnumExtensions 
    { 
     public static IEnumerable<T> GetAllItems<T>(this Enum value) 
     { 
      foreach (object item in Enum.GetValues(typeof(T))) 
      { 
       yield return (T)item; 
      } 
     } 


    } 

    class Program 
    { 

     [Flags] 
     public enum StoreType 
     { 
      Paypal = 1, 
      Plimus = 2, 
      Other = 3 
     }; 

     static void Main(string[] args) 
     {    
      StoreType.GetAllItems //Fail here 
     } 
    } 
} 

回答

1

你必須調用GetAllItems上的值,而不是一個類型:

StoreType.Paypal.GetAllItems() 

但它不會是最好不要讓它的擴展方法連接聲明爲:

public static class EnumExtensions 
{ 
    public static IEnumerable<T> GetAllItems<T>() 
    { 
     foreach (object item in Enum.GetValues(typeof(T))) 
     { 
      yield return (T)item; 
     } 
    } 
} 
static void Main(string[] args) 
{    
    var allEnumItems = EnumExtensions.GetAllItems<StoreType>() 
} 

甚至:

Enum.GetValues(typeof (StoreType)); 
Enum.GetNames(typeof (StoreType)); 

前前後後呃,你可以使用Enum.TryParse(...)將名稱解析回枚舉,我認爲這是你想要的?

1

你看到的編譯器錯誤,因爲你不能覆蓋默認的C#枚舉,根據to this article嘗試重寫你的枚舉這種方式,通過添加方法的自定義類:

public class MyEnum 
{ 
    public static readonly MyEnum A = new MyEnum("A"); 
    public static readonly MyEnum B = new MyEnum("B"); 
    public static readonly MyEnum C = new MyEnum("C"); 
    public static IEnumerable<T> GetAllItems<T>(this Enum value) 
    { 
     foreach (object item in Enum.GetValues(typeof(T))) 
     { 
      yield return (T)item; 
     } 
    } 

    public override string ToString() 
    { 
     return Value; 
    } 

    protected MyEnum(string value) 
    { 
     this.Value = value; 
    } 

    public string Value { get; private set; } 
} 

public sealed class MyDerivedEnum : MyEnum 
{ 
    public static readonly MyDerivedEnum D = new MyDerivedEnum("D"); 

    private MyDerivedEnum(string value) 
     : base(value) 
    { 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyEnum blah = MyEnum.A; 
     System.Console.WriteLine(blah); 
     blah = MyDerivedEnum.D; 
     System.Console.WriteLine(blah); 
    } 
}