0

So I have this struct:

public struct PurchaseOrderStatus {
    public const string Open = "Open", Received = "Received";
}

How do I convert if I have the following:

    string status = "Open";

To:

    PurchaseOrderStatus.Open;

By Convert, I mean, how do I do this:

    PurchaseOrderStatus POS;
    String status = "Open";
    POS = status;
4

1 に答える 1

2

I would suggest using "smart enums" here:

public sealed class PurchaseOrderStatus
{
    public static readonly PurchaseOrderStatus Open =
        new PurchaseOrderStatus("Open");
    public static readonly PurchaseOrderStatus Received =
        new PurchaseOrderStatus("Received");

    private readonly string text;
    public string Text { get { return value; } }

    private PurchaseOrderStatus(string text)
    {
        this.text = text;
    }
}

You can store arbitrary information here, including text which wouldn't be valid identifiers (so long as it doesn't change, of course). It's still strongly typed (unlike your strings) and you can give other behaviour to it. You can even create subclasses if you remove the sealed modifier and add the subclasses as nested classes so they still have access to the private constructor.

Oh, and there's a genuinely limited set of values (the ones you've defined and null) unlike with regular enums.

The only downside is that you can't switch on it.

于 2012-07-23T16:22:20.750 に答える