2015-04-03 69 views
-1

一個很愚蠢的問題...無法在泛型類中創建枚舉?

我試圖讓下面

public static class Component<TClass>where TClass : class 
    { 
     public static void Method<TEnum>() where TEnum : struct, IConvertible, IComparable, IFormattable 
     { 
      if (!typeof(TEnum).IsEnum) 
      { 
       throw new ArgumentException("TEnum must be an enum."); 
      } 
      if (myEnum.Equals(DependencyLifecycle.SingleInstance)) 
      { 
       //do some thingh 
      } 
     } 
    } 

    public enum DependencyLifecycle 
    { 
     SingleInstance, 
     DoubleInstance 
    }; 

像一個泛型類,並試圖援引它作爲

class Program 
    { 
     static void Main(string[] args) 
     { 
      ConsoleApplication1.Component<Program>.Method<DependencyLifecycle.SingleInstance>(); 
     } 
    } 

,但我不能夠正確去做吧。

錯誤

Error 1 'ConsoleApplication1.DependencyLifecycle.SingleInstance' is a 'field' but is used like a 'type' 

Error 2 Operator '==' cannot be applied to operands of type 'System.Type' and 'ConsoleApplication1.DependencyLifecycle' 
+0

請詳細說明「我沒有能力做到這一點。」我們想知道您正在收到哪些錯誤,您嘗試創建枚舉時會發生什麼,以及會發生什麼。 – 2015-04-03 20:09:32

+0

錯誤\t \t 1「ConsoleApplication1.DependencyLifecycle.SingleInstance」是「場」,而是用於像一個「類型」 \t 錯誤\t \t 2操作「==」不能被應用於類型「的System.Type」和'的操作數ConsoleApplication1.DependencyLifecycle' – 2015-04-03 20:10:52

+1

目前尚不清楚爲什麼你在這裏使用泛型或你想要完成什麼。是的,我們看到編譯錯誤,但不知道您的意圖是什麼,建議如何解決問題並非易事。 – vcsjones 2015-04-03 20:16:48

回答

3

你不能提供一個枚舉作爲類型參數的值。你需要它是一個實際的參數。你想要這樣的東西。

public static void Method<TEnum>(TEnum myEnum) 
     where TEnum : struct, IConvertible, IComparable, IFormattable 
    { 
     if (!typeof(TEnum).IsEnum) 
     { 
      throw new ArgumentException("TEnum must be an enum."); 
     } 
     if ((DependencyLifecycle)myEnum== DependencyLifecycle.SingleInstance) 
     { 
      //do some thingh 
     } 
    } 

叫:

ConsoleApplication1.Component<Program>.Method(DependencyLifecycle.SingleInstance); 

(如果它不推斷類型,這樣:)

ConsoleApplication1.Component<Program>.Method<DependencyLifecycle>(DependencyLifecycle.SingleInstance); 
+0

只有這個改變if(myEnum.Equals(DependencyLifecycle.SingleInstance)) – 2015-04-04 05:45:48

2

正如錯誤中明確規定,您要比較枚舉類型的字段值。您的枚舉類型是DependencyLifecycle,您的字段是DependencyLifecycle.SingleInstance。

如果你想檢查它是否是類型DependencyLifecycle,那麼你可以做到這一點

if (typeof(TEnum) == typeof(DependencyLifecycle)) 
{ 
    //do something 
} 
+0

'GetType'在這種情況下也能工作嗎?像'if(typeof(TEnum)== DependencyLifecycle.GetType())'? – 2015-04-03 20:16:21

+0

這是一個枚舉,它沒有一個方法GetType() – 2015-04-03 20:21:11

-1

這種元編程是不是真的常見的C#(因爲總會有更好的方式來做),但是這可能與您想要的最接近:

public static class Component 
{ 
    public static void Method<TEnum>() where TEnum : DependencyLifecycle 
    { 
     if (typeof(TEnum) == typeof(SingleInstanceDependencyLifecycle)) 
     { 
      // do something with SingleInstance 
     } 
    } 
} 

public abstract class DependencyLifecycle { } 
public sealed class SingleInstanceDependencyLifecycle : DependencyLifecycle { } 
public sealed class DoubleInstanceDependencyLifecycle : DependencyLifecycle { } 
相關問題