首页 > 后端开发 > C++ > 如何更优雅地获得C#中的枚举的字符串表示?

如何更优雅地获得C#中的枚举的字符串表示?

Susan Sarandon
发布: 2025-01-29 07:57:09
原创
296 人浏览过

How Can I Get the String Representation of an Enum in C# More Elegantly?

优雅地获取C#枚举的字符串表示

考虑以下枚举:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}
登录后复制

要获取字符串值(例如“FORMS”而不是ID 1),需要自定义解决方案。虽然现有的基于属性的方法和字典方法提供了变通方案,但存在更优雅的解决方案。

类型安全枚举模式

类型安全枚举模式引入一个密封类,将每个枚举成员表示为单独的实例:

public sealed class AuthenticationMethod
{
    private readonly string name;
    private readonly int value;

    public static readonly AuthenticationMethod FORMS = new AuthenticationMethod(1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod(2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod(3, "SSN");

    private AuthenticationMethod(int value, string name)
    {
        this.name = name;
        this.value = value;
    }

    public override string ToString()
    {
        return name;
    }
}
登录后复制

这种模式具有以下优点:

  • 类型安全:AuthenticationMethod类确保只使用有效值。
  • 清晰简洁:字符串表示直接与每个成员关联。
  • 可扩展性:可以添加附加值而不会破坏现有代码。

显式类型转换

如果需要,可以向AuthenticationMethod类添加显式类型转换,允许进行字符串到枚举的转换(此部分代码示例中存在问题,需要修正):

// 修正后的显式类型转换
private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string, AuthenticationMethod>()
{
    {"FORMS", FORMS},
    {"WINDOWS", WINDOWSAUTHENTICATION},
    {"SSN", SINGLESIGNON}
};

public static explicit operator AuthenticationMethod(string str)
{
    if (instance.TryGetValue(str, out var result))
        return result;
    else
        throw new InvalidCastException();
}
登录后复制

这允许方便地进行转换,例如:

AuthenticationMethod method = (AuthenticationMethod)"FORMS";
登录后复制

以上是如何更优雅地获得C#中的枚举的字符串表示?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板