开发者

How should I encapsulate this multi-dimensional enum?

开发者 https://www.devze.com 2023-01-28 06:54 出处:网络
In my application I\'ve got some information that can be one of a small set of values - so I\'d like to use an enum to hold it, ensuring valid values through type-safety at compile time:

In my application I've got some information that can be one of a small set of values - so I'd like to use an enum to hold it, ensuring valid values through type-safety at compile time:

public enum Something { A1, A2, A3, B1, B2, C1 };

These enums represent multi-dimensional data (they have a letter and a number in the example above), so I'd like to be able to get the value associated with them, e.g.

Something example = Something.A1;
// Now I want to be able to query the values for example:
example.Letter; // I want to get "A"
example.Number; // "1"I want to get 1

I've two possible solutions, neither of them feel very 'clean', so I was interested in which people prefer, and why, or whether anyone has any better ideas.

Option 1: Create a struct which wraps the enum, and provides properties on the wrapped data, e.g.

public struct SomethingWrapper
{
    public Something Value { get; private set; }

    publ开发者_Go百科ic SomethingWrapper(Something val)
    {
        Value = val;
    }

    public string Letter
    {
        get
        {
            // switch on Value...
        }
    }

    public int Number
    {
        get
        {
            // switch on Value...
        }
    }
}

Option 2: Leave the enum as it is and create a static Helper class which provides static functions that get the values:

public static class SomethingHelper
{
    public static string Letter(Something val)
    {
        // switch on val parameter
    }

    public static int Number(Something val)
    {
        // switch on val parameter
    }
}

Which should I choose, and why? Or is there a better solution I've not thought of?


Third option: like the second option, but with extension methods:

public static class SomethingHelper
{
    public static string Letter(this Something val)
    {
        // switch on val parameter
    }

    public static int Number(this Something val)
    {
        // switch on val parameter
    }
}

Then you can do:

Something x = ...;
string letter = x.Letter();

It's unfortunate that there aren't extension properties, but such is life.

Alternatively, create your own pseudo enum: something like this:

public sealed class Something 
{
    public static Something A1 = new Something("A", 1);
    public static Something A2 = ...;

    private Something(string letter, int number)
    {
        Letter = letter;
        Number = number;
    }

    public string Letter { get; private set; }
    public int Number { get; private set; }
}


Why not just use two enums, and maybe define a struct that holds one of each?

0

精彩评论

暂无评论...
验证码 换一张
取 消