简体   繁体   English

具有“选择”的C#自定义数据类型

[英]C# Custom datatype with “choices”

I need a custom datatype for order status, how can this be done in C#? 我需要一个用于订单状态的自定义数据类型,该如何在C#中完成? Below is an example of what I mean. 以下是我的意思的示例。

Order can be in 4 states: 订单可以处于4个状态:
- In queue -排队中
- Handling -处理
- Shipping - 运输
- Received -收到

class Order {
    public OrderStatus status { get; set; }
}

Order myorder = new Order();
myorder.status = OrderStatus.queue;

...

if (myorder.status == OrderStatus.received) 
{
    ...
}

How to define the OrderStatus class so it has those four options to select from? 如何定义OrderStatus类,使其具有这四个选项可供选择?

Cheers 干杯

enum OrderStatus {
    InQueue,
    Handling,
    Shipping,
    Received
}
  • You may or may not need to mark it public depending on your needs 您可以根据需要将其标记为公开,也可以不标记为公开
  • You may or may not need to set specific integer values to each of the enum items. 您可能需要也可能不需要为每个枚举项设置特定的整数值。 Once you start persisting them you never (well, would be easier not to) want to change the order. 一旦开始保留它们,您就再也不想更改顺序了(很容易,不用这样)。 By assigning specific values can allow you to re-order and group them in ways that might make sense etc... 通过分配特定的值可以使您以可能有意义的方式对它们进行重新排序和分组...

As an Example: 举个例子:

enum OrderStatus {
    NewOrder = 1,

    OnHold = 6,
    CancelledOrder = 9,

    // Approval States
    WaitingApproval = 7,
    ApprovalRejected = 8,

    // Processing
    InQueue = 2,
    Handling = 3,

    // We've done our job!
    Shipping = 4,
    Received = 5
}

Use an enumeration, which is a "collection of possible values" 使用枚举,即“可能值的集合”

public enum OrderStatus
{
    InQueue,
    Handling,
    Shipping,
    Received
}

A variable of that type would be used like: 该类型的变量的用法如下:

public OrderStatus myStatus;
myStatus = OrderStatus.Shipping;

if (myStatus == OrderStatus.Shipping)
   ...

Declare enumeration: 声明枚举:

public enum OrderStatus
{
    InQueue,
    Handling,
    Shipping,
    Received 
}

Here you can read more. 在这里您可以阅读更多。

Use an Enum for that: 为此使用一个枚举:

public enum Orderstatus{ 
    InQueue, 
    Handling, 
    Shipping, 
    Received 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM