How to maintain interlink between multiple enums in c#

时间:2017-04-10 01:23:11

标签: c# enums

I'm new to c#, in java we used to have interlinking for enums like below:

 public enum Module
{
    None(SubModule.None),
    Authentication(SubModule.Login),
    User(SubModule.User,SubModule.ForgotPassword,SubModule.ResetPassword)


    private SubModule subModule;

    public Module(SubModule... submodule)
    {

    }

 }

I want to interlink my Modules with submodules, I tried the same in C# its giving compilation error. Is there anyway to do the same in C#.

1 个答案:

答案 0 :(得分:1)

C# enums are much simpler types than Java enums - they cannot have constructors, methods, or member fields. However, you can achieve similar functionality using a class with static instances that represent each "enumeration."

public sealed class Module
{
    public static Module None { get; } = new Module(SubModule.None);
    public static Module Authentication { get; } = new Module(SubModule.Login);
    public static Module User { get; } = new Module(SubModule.User, SubModule.ForgotPassword, SubModule.ResetPassword);

    private SubModule[] _subModules;
    private Module(params SubModule[] subModules)
    {
        _subModules = subModules;
    }
}

This class allows you to access the static Module instances using basically the same syntax as an enumeration, and the private constructor prevents new instances from being created.

Note that SubModule could be a true C# enum if that suits your needs, or it could also be a class with static properties for "enum" values.