3

我有以下枚举:

public enum DocumentState
{
    Default = 0,
    Draft = 1,
    Archived = 2,
    Deleted = 3
}

我的解决方案中的大多数地方都将其用作普通枚举。我在 int 中使用的一些地方是这样的:

(int)DocumentState.Default)

但是,在某些地方,例如当我使用 Examine (只接受字符串,而不是整数作为输入)时,我需要传递 enumns int 值,就好像它是一个字符串一样。这可以通过以下方式完成:

((int)DocumentState.Default).ToString()

我现在的问题是;真的没有其他方法可以将枚举值作为字符串检索吗?

我知道我可能在滥用枚举,但有时这是给定情况下的最佳方法。

4

5 回答 5

9

使用DocumentState.Default.ToString("d"). 请参阅https://msdn.microsoft.com/en-us/library/a0h36syw(v=vs.110).aspx

于 2016-04-08T11:55:16.450 回答
0

好像你滥用枚举。如果您需要存储其他信息,请使用真实类。在这种情况下,您的Document-class 可能有一个State-property,它返回一个具有-enumDocumentState属性的类的实例。DocStateType然后你可以添加额外的信息,TypeId如果需要的话,获取字符串的代码非常简单易读:

public class Document
{
    public int DocumentId { get; set; }
    public DocumentState State { get; set; }
    // other properties ...
}


public enum DocStateType
{
    Default = 0,
    Draft = 1,
    Archived = 2,
    Deleted = 3
}

public class DocumentState
{
    public DocumentState(DocStateType type)
    {
        this.Type = type;
        this.TypeId = (int) type;
    }
    public DocumentState(int typeId)
    {
        if (Enum.IsDefined(typeof (DocStateType), typeId))
            this.Type = (DocStateType) typeId;
        else
            throw new ArgumentException("Illegal DocStateType-ID: " + typeId, "typeId");
        this.TypeId = typeId;
    }

    public int TypeId { get; set; }
    public DocStateType Type { get; set; }
    // other properties ...
}

如果你想要TypeId你只需要的 as 字符串doc.State.TypeId.ToString(),fe:

Document doc = new Document();
doc.State = new DocumentState(DocStateType.Default);
string docTypeId = doc.State.TypeId.ToString();

这种方法将枚举值用作TypeId,通常您不会将枚举值用于您的业务逻辑。所以他们应该是独立的。

于 2016-04-08T12:09:56.517 回答
-1

就个人而言,我认为你试图用你的 Enum 做的并不是最好的方法。你可以做的是创建一个类Dictionary<TKey, TValue>来保存你的键和值。

在 C# 6 或更高版本中:

static class DocumentState {
    public static Dictionary<string, int> States { get; } = new Dictionary<string, int>() { { "Default", 0 }, { "Draft", 1 }, { "Archived", 2 }, { "Deleted", 3 } };
}

C# 5 或更低版本:

class DocumentState {
    public Dictionary<string, int> State { get; }

    public DocumentState() {
        State = new Dictionary<string, int>() { { "Default", 0 }, { "Draft", 1 }, { "Archived", 2 }, { "Deleted", 3 } };
    }
}

这样您就可以随时调用您的字典键来检索所需的值,而不会错误地覆盖字典的默认值。

于 2016-04-08T12:14:39.797 回答
-2

您可以使用Enum.GetName方法

于 2016-04-08T11:52:42.513 回答
-3

您可以引用System.Runtime.Serialization和使用该EnumMember属性。

public enum foonum
{
    [EnumMember(Value="success")]
    success,
    [EnumMember(Value="fail")]
    fail
}

Console.WriteLine (foonum.success);

产生:“成功”

于 2016-04-08T11:49:44.853 回答