What is the correct way to get my custom enumeration classes by their value?

I created my own pseudo-enumerations in my domain model to allow me to have a few more verbose values. For example, my class looks like this:

public abstract class Enumeration<X, Y> : IComparable where X : IComparable
{

    public Enumeration(X value, Y displayName) { }

    public Y DisplayName { get { return _displayName; } }
    public X Value { get { return _value; } }

}

And the class that inherits it will be:

public class JobType : Enumeration<string, string>
{
    public static JobType ChangeOver = new JobType("XY01", "Changeover");
    public static JobType Withdrawal = new JobType("XY02", "Withdrawal");
    public static JobType Installation = new JobType("XY03", "Installation");

    private JobType(string jobTypeId, string description)
        : base(jobTypeId, description) { }
}

The problem is that I want to be able to resolve these values ​​from the value returned from the database in my repository. So I get a method like:

public static JobType Resolve(string jobTypeId) { return matchingJobType; }

I started writing a resolution method for each enumeration class, but there should be a better way than duplicating the same method with the switch statement in each?

Dictionary<X, Enumeration<X, Y>> Cache; . . , , Enumeration<X, Y>, JobType.

, , Enumeration, :

public static T Resolve(X value); // With the additional type
public static T Resolve<T>(X value); // Or without an additional type

JobType.Resolve<JobType>(foo);, JobType.Resolve(foo);, . ?

+2
2

. , , , , , .

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
}

.

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

Resolve.

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

, . , , , , .

+3

, , , , DAL :

public enum JobType
{
    ChangeOver,
    Withdrawal,
    Installation,
}

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

(, ) / .

JobType (, "ChangeOver" ), Enum.Parse/Enum.TryParse casting.

, , , / .

0

Source: https://habr.com/ru/post/1759013/


All Articles