开发者

Public Enumeration with only string values

I'm always confused which kind of enumeration I should use. A hashtable, an enum, a struct a dictionary, an array (how oldschool), static strings...

Instead of using strings in my code I want to use a beautiful enum like so:

public enum MyConfigs
{
    Configuration1,
    Configuration2
}

Pro开发者_开发百科blem is that I don't always want to convert my enum toString() as I'm not interested in the index representation of the enum.

What is the best way to represent a public enumeration of string based values?

In the end I would love to end up with using MyConfigs.Configuration1 where needed in my code.


I prefer defining "grouped" constants as static members of a dummy static class, like so:

public static class FieldNames
{
    public const string BRANCH_CODE = "_frsBranchCode";
    public const string BATCH_ID = "_frsBatchId";
    public const string OFFICE_TYPE = "_frsOfficeType";
}

But of course they are not "enumerable" directly, so you can't foreach over them unless you provide a static array too:

public static string[] AllFieldNames
{
    get
    {
        return new string[]
        {
            FieldNames.BRANCH_CODE,
            FieldNames.BATCH_ID,
            FieldNames.OFFICE_TYPE
        };
    }
}


public static class MyConfigs
{
    public const string Configuration1 = "foo",
                        Configuration2 = "bar"
}

This is then pretty-much identical to how enums are implemented (ignoring the whole "it must be an integer" thing).


Type-safe enum pattern?

public class StringEnum
{
    #region Enum Values

    public static readonly StringEnum ValueOne = new StringEnum("Value One");
    public static readonly StringEnum ValueTwo = new StringEnum("Value Two");

    #endregion

    #region Enum Functionality

    public readonly string Value;

    private StringEnum(string value)
    {
        Value = value;
    }

    public override string ToString()
    {
        return value;
    }

    #endregion
}

You can use this like:

private void Foo(StringEnum enumVal)
{
  return "String value: " + enumVal;
}

If you never need to pass these values around in a type-safe manner to methods etc. then it is probably best to just stick with a constants file.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜