2015-04-03 68 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 { } 
相关问题