What's the correct way of retrieving my custom enumeration classes by their value?

风格不统一 提交于 2019-12-02 03:31:13

This looks like a situation for the curiously recurring template pattern. If you want to get the base type method to return the derived class without casting, then you can pass the derived type into the base type, constraining the derived type to to be derived from the base type, e.g.

public abstract class Enumeration<TEnum, X, Y> : IComparable 
    where TEnum : Enumeration<TEnum, X, Y>
    where X : IComparable
{
    public static TEnum Resolve(X value) { /* your lookup here */ }

    // other members same as before; elided for clarity
}

You'd then define your concrete classes as follows.

public class JobType : Enumeration<JobType, string, string>
{
    // other members same as before; elided for clarity
}

Now your types will match up and no casting required on the base class Resolve method.

JobType type = JobType.Resolve("XY01");

How you store the value to instance mapping in the base class is up to you. It sounds like you already know how to do this anyway, and just needed a bit of help with getting the types to match up.

Your real enumeration class may be more complicated than this, but your current implementation looks like it could be defined much more simply as a standard enumeration coupled with a DAL pattern, or simply a dictionary:

public enum JobType
{
    ChangeOver,
    Withdrawal,
    Installation,
}

// Maybe inside some DAL-pattern/database parsing class:
var databaseToJobTypeMap = new Dictionary<string, JobType>()
{
    { "XY01", JobType.ChangeOver },
    // ...
};

Keeping the parsing code together (maybe with an interface abstraction) gives you the option to switch parsers when your data storage format/needs change, or if you end up having multiple data sources.

If you need to parse the actual JobType values (for example, the string "ChangeOver" or an integer representation), then you can use Enum.Parse/Enum.TryParse, or casting.

The implementation you have seems to be more inflexible, because it locks the enumeration type to one dictionary mapping style/representation.

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