如何返回“无”?作为工厂的默认案例? [英] How can I return "none" as a default case from a factory?

查看:45
本文介绍了如何返回“无”?作为工厂的默认案例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码(其背后的整个故事都在这里: https:// codereview.stackexchange.com/questions/28990/fancy-pants-vs-cowboy-coding ):

I have this code (the whole story behind it is here: https://codereview.stackexchange.com/questions/28990/fancy-pants-vs-cowboy-coding):

public class BeltPrinterFactory : IBeltPrinterFactory
{
    public IBeltPrinter NewBeltPrinter()
    {
        switch (printerChoice)
        {
            case BeltPrinterType.ZebraQL220: 
                return new ZebraQL220Printer();
            case BeltPrinterType.ONiel: 
                return new ONielPrinter();
            default: 
                return new ZebraQL220Printer();
        }
    }
}

...但已添加枚举为无,因为许多客户将不使用/使用一个枚举:

...but have added a "None" to the enum, as many customers will not have/use one:

public enum BeltPrinterType
{
    None,
    ZebraQL220,
    ONiel
    // add more as needed
}

编译器不允许我没有默认大小写(并非所有代码路径都返回值)。

The compiler won't allow me to not have a default case ("not all code paths return a value").

None选项可能应该是默认情况,但是如果 None是printerChoice的当前值,则永远不要调用工厂(当 None为值时,甚至不会显示开始滚球的GUI ),但为了编译器的缘故,应如何实现呢?我能以某种方式退还任何东西吗?还是我需要做一些怪异的事情,例如:

The "None" option perhaps should be the default case, but if None is the current value of printerChoice, the factory should never be called (the GUI that starts that ball rolling won't even be displayed when "None" is the value), but for the compiler's sake, how should this be implemented? Can I return nothing somehow? Or will I need to do something "weird" like:

    . . .
    default: 
        return new None();
    . . .

public class None : IBeltPrinter
{
    public void PrintLabel(string price, string description, string barcode)
    {
        ;// do nothing
    }
}


推荐答案

如果不允许为工厂选项,引发异常。

如果对工厂,返回 IBeltPrinter 的虚拟实现。

返回 null

If None isn't allowed option for factory, throw an exception.
If None is valid for factory, return dummy implementation of IBeltPrinter.
Do not return null.

这篇关于如何返回“无”?作为工厂的默认案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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