Define “dynamic” enum

ぃ、小莉子 提交于 2019-12-13 00:23:05

问题


I'm working on this project and I have a large number of "services" to execute. I need to have this service codes so I can verifiy and make decisions according to selected services by it's code.

I'm tring to define this enum and get its values from the web.config so I can change them easily.

public enum ServiceCodes
{
    Transfer= Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"]),
    ChangePlate= Convert.ToInt32(ConfigurationManager.AppSettings["servChangePlate"])
}

But I get this error: The expression must be constant. (because of the Conversion)

What can I do? (Or you can suggest me totally different approaches.)


回答1:


Just go ahead and define a static class like this:

public static class ServiceCodes
{
  readonly static int Transfer = Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"])
  //...
}



回答2:


The documentation states that enum values are constant. An alternative approach is to declare a class with static readonly members.

If you still need the type safety provided by an enum, you could use a slightly complex approach:

public class ServiceCodes {

    public static readonly ServiceCodes Transfer = new ServiceCodes(Convert.ToInt32(ConfigurationManager.AppSettings["servTransfer"]));
    public static readonly ServiceCodes ChangePlate = new ServiceCodes(Convert.ToInt32(ConfigurationManager.AppSettings["servChangePlate"]));

    internal int Code {get; private set;}

    private ServiceCodes(int code) {
        Code = code;
    }
}

Then, a method like:

public void SomeAction(ServiceCodes serviceCode) {
    //....  
}

could be called like this:

SomeAction(ServiceCodes.Transfer);

But, given the complexity (compared with the gain), I would go with the first approach.



来源:https://stackoverflow.com/questions/3898217/define-dynamic-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!