模仿枚举实现接口的行为 [英] Behaviour to simulate an enum implementing an interface

查看:85
本文介绍了模仿枚举实现接口的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个类似的枚举:

Say I have an enum something like:

enum OrderStatus
{
    AwaitingAuthorization,
    InProduction,
    AwaitingDespatch
}

我还在枚举上创建了一个扩展方法,以整理UI中显示的值,所以我有类似的东西:

I've also created an extension method on my enum to tidy up the displayed values in the UI, so I have something like:

public static string ToDisplayString(this OrderStatus status)
{
    switch (status)
    {
        case Status.AwaitingAuthorization:
            return "Awaiting Authorization";

        case Status.InProduction:
            return "Item in Production";

        ... etc
    }
}

灵感源自出色的帖子

Inspired by the excellent post here, I want to bind my enums to a SelectList with an extension method:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)

但是,要在UI下拉菜单中使用DisplayString值,我需要沿着以下行添加约束

however, to use the DisplayString values in the UI drop down I'd need to add a constraint along the lines of

: where TEnum has extension ToDisplayString

显然,在当前方法中,所有这些都不起作用,除非有我不知道的一些巧妙技巧.

Obviously none of this is going to work at all with the current approach, unless there's some clever trick I don't know about.

有人对我如何实现这样的东西有任何想法吗?

Does anyone have any ideas about how I might be able to implement something like this?

推荐答案

是否有充分的理由在此处使用enum?

Is there a compelling reason to use an enum here?

当您开始跳过疯狂的篮球来使用enum时,可能是时候使用课程了.

When you start jumping through crazy hoops to use enums, it might be time to use a class.

public class OrderStatus
{
    OrderStatus(string display) { this.display = display; }

    string display;

    public override string ToString(){ return display; }

    public static readonly OrderStatus AwaitingAuthorization
        = new OrderStatus("Awaiting Authorization");
    public static readonly OrderStatus InProduction
        = new OrderStatus("Item in Production");
    public static readonly OrderStatus AwaitingDispatch
        = new OrderStatus("Awaiting Dispatch");
}

您使用它的方式与enum相同:

You consume it the same as an enum:

public void AuthorizeAndSendToProduction(Order order, ProductionQueue queue)
{
    if(order.Status != OrderStatus.AwaitingAuthorization) 
    {
        Console.WriteLine("This order is not awaiting authorization!");
        return;
    }
    order.Status = OrderStatus.InProduction;
    queue.Enqueue(order);
}

字符串表示形式是内置的,您只需要ToString().

The string representation is built-in, and all you need is ToString().

这篇关于模仿枚举实现接口的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆