C# enums as function parameters?

后端 未结 7 1376
广开言路
广开言路 2021-01-04 00:10

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

For example:

enum e1
{
    //...
}

enum e2
{
    //...
}

public void test()
{
    myFunc( e1 );
           


        
相关标签:
7条回答
  • 2021-01-04 00:12

    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"
    
    0 讨论(0)
  • 2021-01-04 00:12

    correct is:

    public void myFunc(Enum e)
    {
        foreach (var name in Enum.GetNames(e.GetTye()))
        {
            Console.WriteLine(name);
        }
    }
    
    0 讨论(0)
  • 2021-01-04 00:16

    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.

    0 讨论(0)
  • 2021-01-04 00:17

    You mean something like Enum.GetNames?

    0 讨论(0)
  • 2021-01-04 00:18

    Enum.GetValues Enum.GetNames

    so something like...

    foreach(e1 value in Enum.GetValues(typeof(e1)))
    
    0 讨论(0)
  • 2021-01-04 00:23

    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.

    0 讨论(0)
提交回复
热议问题