c#枚举功能参数

时间:2009-02-03 14:58:05

标签: c# enums function-parameter

来自this question.

的后续内容

如何调用函数并传入枚举?

例如,我有以下代码:

enum e1
{
    //...
}

public void test()
{
    myFunc( e1 );
}

public void myFunc( Enum e )
{
    var names = Enum.GetNames(e.GetType());

    foreach (var name in names)
    {
        // do something!
    }

}

虽然当我这样做时,我得到'e1'是'type'但是被用作'变量'错误消息。有什么想法可以提供帮助吗?

我试图将函数保持通用,以便在任何Enum上工作,而不仅仅是特定的类型?这甚至可能吗?...使用通用功能怎么样?这会有用吗?

4 个答案:

答案 0 :(得分:9)

为什么不传递类型? 像:

 myfunc(typeof(e1));

public void myFunc( Type t )
{
}

答案 1 :(得分:9)

您可以使用通用功能:

    public void myFunc<T>()
    {
        var names = Enum.GetNames(typeof(T));

        foreach (var name in names)
        {
            // do something!
        }
    }

并打电话:

    myFunc<e1>();

(适用EDIT)

如果您尝试将T约束为Enumenum,编译器会抱怨。

因此,为确保类型安全,您可以将功能更改为:

    public static void myFunc<T>()
    {
        Type t = typeof(T);
        if (!t.IsEnum)
            throw new InvalidOperationException("Type is not Enum");

        var names = Enum.GetNames(t);
        foreach (var name in names)
        {
            // do something!
        }
    }

答案 2 :(得分:5)

您正在尝试将枚举的类型作为该类型的实例传递 - 尝试这样的事情:

enum e1
{
    foo, bar
}

public void test()
{
    myFunc(e1.foo); // this needs to be e1.foo or e1.bar - not e1 itself
}

public void myFunc(Enum e)
{
    foreach (string item in Enum.GetNames(e.GetType()))
    {
        // Print values
    }
}

答案 3 :(得分:0)

使用

public void myFunc( e1 e ) { // use enum of type e}

而不是

public void myFunc( Enum e ) { // use type enum. The same as class or interface. This is not generic! }