C#中枚举的替代方法 - 嵌套

时间:2016-07-30 12:50:12

标签: c# enums static c#-6.0

遇到这篇有趣的文章:

Alternative to enum by Ardalis

如何才能在类中嵌套类。

假设我们对每个角色都有不同的状态:作者,编辑。

  

作者:经验丰富,精英

     

编辑:批准,偶然

如何以%:

的形式访问该值
  

Role.Author.Seasoned.Value

     

Role.Editor.Approved.Value

由于

1 个答案:

答案 0 :(得分:3)

我不明白这个问题。如果要使用嵌套类,请使用嵌套类。从您链接到的文章的设计开始,您将获得:

public class Role
{
    public static class Author
    {
        public static Role Seasoned {get;} = new Role(0, "Seasoned author");
        public static Role Elite {get;} = new Role(1, "Elite author");
    }

    public static class Editor
    {
        public static Role Approved {get;} = new Role(2, "Approved editor");
        public static Role Occassional {get;} = new Role(3, "Occassional editor");
    }

    public string Name { get; private set; }
    public int Value { get; private set; }

    private Role(int val, string name) 
    {
        Value = val;
        Name = name;
    }

    public IEnumerable<Role> List()
    {
        return new[]{Author.Seasoned,Author.Elite,Editor.Approved,Editor.Occassional};
    }

    public Role FromString(string roleString)
    {
        return List().FirstOrDefault(r => String.Equals(r.Name, roleString, StringComparison.OrdinalIgnoreCase));
    }

    public Role FromValue(int value)
    {
        return List().FirstOrDefault(r => r.Value == value);
    }
}