开发者

How do I pass an Enum as an argument?

开发者 https://www.devze.com 2023-03-28 13:22 出处:网络
In the code below I am just coverting a string (\"medium\" for example) to its Enum value.What I need to be able to do is rather than having Opacity as a fixed Enum type, pass that in as an argument a

In the code below I am just coverting a string ("medium" for example) to its Enum value. What I need to be able to do is rather than having Opacity as a fixed Enum type, pass that in as an argument as well so that the function oper开发者_运维知识库ates on any Enum. This seems to be proving more difficult than I anticipated, i.e. 'Enum MyEnum' doesn't work. Solutions anyone?

public enum Opacity
{
    Low,
    Medium,
    High
}

public static Enum StringToEnum(String str)
{            
    return (Opacity)Enum.Parse(typeof(Opacity), str, true);  // Case insensitive             
}


public static T StringToEnum<T>(String str) where T : struct
{
    return (T)Enum.Parse(typeof(T), str, true);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消