无法在Generic Class中创建枚举?

时间:2015-04-03 20:07:46

标签: c#

一个非常愚蠢的问题......

我正在尝试制作类似下面的通用类

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'

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

由于错误明确指出,您正在尝试将枚举类型与字段值进行比较。这里的枚举类型是DependencyLifecycle,你的字段是DependencyLifecycle.SingleInstance。

如果您要检查它是否为DependencyLifecycle类型,那么您可以执行此操作

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

答案 2 :(得分:-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 { }