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

后端 未结 2 1185
一生所求
一生所求 2021-01-21 12:26

I\'ve created my own custom pseudo enumerations within my domain model to allow me to have some more verbose values. For example, my class is as follows:

public          


        
2条回答
  •  不要未来只要你来
    2021-01-21 12:44

    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 : IComparable 
        where TEnum : Enumeration
        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
    {
        // 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.

提交回复
热议问题