如何传递枚举作为参数?

发布于 2024-11-29 15:11:35 字数 377 浏览 0 评论 0原文

在下面的代码中,我只是将字符串(例如“medium”)转换为其枚举值。我需要做的不是将 Opacity 作为固定的 Enum 类型,而是将其作为参数传递,以便该函数可以对任何 Enum 进行操作。这似乎比我预期的更困难,即“Enum MyEnum”不起作用。有人解决吗?

public enum Opacity
{
    Low,
    Medium,
    High
}

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-12-06 15:11:35
public static T StringToEnum<T>(String str) where T : struct
{
    return (T)Enum.Parse(typeof(T), str, true);
}
public static T StringToEnum<T>(String str) where T : struct
{
    return (T)Enum.Parse(typeof(T), str, true);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文