2011-02-16 153 views
2

enum幫手泛型類在那裏我有方法EnumDescription() 要調用它,我必須去這樣EnumHelper<Enumtype>.EnumDescription(value) 我想要實現enum擴展,它基於我的枚舉的輔助方法方法EnumDescription(this Enum value)EnumHelper<T>.EnumDescription(value)幫助枚舉擴展方法

有一件事我被困住了。這裏是我的代碼:

public static string EnumDescription(this Enum value) 
{ 
    Type type = value.GetType(); 

    return EnumHelper<type>.EnumDescription(value); //Error here 
} 

我得到一個錯誤The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)

,請問有什麼可以做,使工作?

+0

你想給Enum一個很好的描述? – PostMan 2011-02-16 00:26:05

回答

3

我能想到的兩個選項(可能還有更多)。

第一個選項:使通用擴展方法。 C#不允許enum作爲通用約束,這意味着您需要運行時檢查以確保該類型實際上是enum

public static string EnumDescription<T>(this T value) 
    where T : struct, IComparable, IConvertible, IFormattable 
{ 
    if (!typeof(T).IsEnum) 
     throw new InvalidOperationException("Type argument T must be an enum."); 

    return EnumHelper<T>.EnumDescription(value); 
} 

第二個選項:使用反射。這將會很慢(呃),儘管你可以從MethodInfo創建一個代理並將其緩存以便在Dictionary<Type, Delegate>或類似的地方重新使用。這種方式只會在第一次遇到特定類型時產生反射成本。

public static string EnumDescription(this Enum value) 
{ 
    Type t = value.GetType(); 
    Type g = typeof(EnumHelper<>).MakeGenericType(t); 
    MethodInfo mi = g.GetMethod("EnumDescription"); 
    return (string)mi.Invoke(null, new object[] { value }); 
} 
+0

你認爲哪個選項更好? – Jop 2011-02-16 01:08:15

1

泛型是在編譯時完成的。

您可以將您的方法更改爲通用方法where T : struct或使用反射調用內部方法。