C# 枚举作为函数参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/492115/
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 05:30:21  来源:igfitidea点击:

C# enums as function parameters?

c#enumsloopsfunction-parameter

提问by TK.

Can you pass a standard c# enum as a parameter?

你能传递一个标准的 c# 枚举作为参数吗?

For example:

例如:

enum e1
{
    //...
}

enum e2
{
    //...
}

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

public void myFunc( Enum e )
{
    // Iterate through all the values in e
}

By doing this I hope to retrieve all the names within any given enum. What would the Iteration code look like?

通过这样做,我希望检索任何给定枚举中的所有名称。迭代代码会是什么样子?

采纳答案by Daniel Schaffer

This!

这个!

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

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

EDIT: My bad, you didsay iterate.

编辑:我的错,你确实说过iterate

Note: I know I could just do the GetNames() call in my foreach statement, but I prefer to assign that type of thing to a method call first, as it's handy for debugging.

注意:我知道我可以只在 foreach 语句中调用 GetNames(),但我更喜欢先将这种类型的东西分配给方法调用,因为它便于调试。

回答by pezi_pink_squirrel

Use the Enum.GetNames( typeof(e) ) method, this will return an array of strings with the names.

使用 Enum.GetNames( typeof(e) ) 方法,这将返回一个带有名称的字符串数组。

You can also use Enum.GetValues to obtain the counterpart values.

您还可以使用 Enum.GetValues 来获取对应的值。

Edit -Whoops - if you are passing the parameter as Enum, you will need to use e.GetType() instead of typeof() which you would use if you had passed the parameter in as the actual Enum type name.

编辑 -Whoops - 如果您将参数作为 Enum 传递,则需要使用 e.GetType() 而不是 typeof() ,如果您将参数作为实际的 Enum 类型名称传入,则会使用它。

回答by ctacke

You mean something like Enum.GetNames?

你是说 Enum.GetNames 之类的东西?

回答by Luke

Enum.GetValues Enum.GetNames

Enum.GetValues Enum.GetNames

so something like...

所以像...

foreach(e1 value in Enum.GetValues(typeof(e1)))

回答by bruno conde

Like this:

像这样:

    public void myFunc(Enum e)
    {
        foreach (var name in Enum.GetNames(typeof(e)))
        {
            Console.WriteLine(name);
        }
    }

回答by bruno conde

correct is:

正确的是:

public void myFunc(Enum e)
{
    foreach (var name in Enum.GetNames(e.GetTye()))
    {
        Console.WriteLine(name);
    }
}

回答by gg89

You will have trouble if you try passing an enumdirectly to myFunc, as in the following example:

如果您尝试将enum直接传递给myFunc,则会遇到问题,如下例所示:

enum e1 {something, other};
myFunc(e1);  // Syntax error: "e1 is a type, but is being used like a variable"