c# Enum Function Parameters

家住魔仙堡 提交于 2019-12-09 11:47:48

问题


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?

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?


回答1:


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 T to Enum or 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!
        }
    }



回答2:


Why not passing the type? like:

 myfunc(typeof(e1));

public void myFunc( Type t )
{
}



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/507396/c-sharp-enum-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!