C# enums as function parameters?

泄露秘密 提交于 2019-11-30 17:11:37

This!

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

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

EDIT: My bad, you did say 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.

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

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

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.

You mean something like Enum.GetNames?

Enum.GetValues Enum.GetNames

so something like...

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

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

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

Like this:

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

correct is:

public void myFunc(Enum e)
{
    foreach (var name in Enum.GetNames(e.GetTye()))
    {
        Console.WriteLine(name);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!