c#枚举函数参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/507396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:07:36  来源:igfitidea点击:

c# Enum Function Parameters

c#enumsfunction-parameter

提问by TK.

As a follow on from this question.

作为这个问题的后续

How can I call a function and pass in an Enum?

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

For example I have the following code:

例如,我有以下代码:

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!
    }

}

Although when I do this I am getting the 'e1' is a 'type' but is used like a 'variable' Error message. Any ideas to help?

虽然当我这样做时,我得到的 'e1' 是一个 'type',但它被用作一个 'variable' 错误消息。有什么想法可以帮助吗?

I am trying to keep the function generic to work on any Enum not just a specific type? Is this even possible?... How about using a generic function? would this work?

我试图保持函数通用以适用于任何 Enum 而不仅仅是特定类型?这甚至可能吗?...如何使用通用函数?这行得通吗?

采纳答案by bruno conde

You can use a generic function:

您可以使用通用函数:

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

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

and call like:

并调用:

    myFunc<e1>();

(EDIT)

(编辑)

The compiler complains if you try to constraint Tto Enumor enum.

如果您尝试约束TEnum或,编译器会抱怨enum

So, to ensure type safety, you can change your function to:

因此,为了确保类型安全,您可以将函数更改为:

    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!
        }
    }

回答by Andrew Hare

You are trying to pass the type of the enum as an instance of that type - try something like this:

您正在尝试将枚举类型作为该类型的实例传递 - 尝试如下操作:

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
    }
}

回答by Martin Moser

Why not passing the type? like:

为什么不传递类型?喜欢:

 myfunc(typeof(e1));

public void myFunc( Type t )
{
}

回答by abatishchev

Use

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

instead of

代替

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