C# 我怎样才能返回;无”;作为工厂的默认情况?
我有这个代码(它背后的全部故事在这里:): …但已将“无”添加到枚举中,因为许多客户不会拥有/使用:C# 我怎样才能返回;无”;作为工厂的默认情况?,c#,enums,factory,factory-pattern,C#,Enums,Factory,Factory Pattern,我有这个代码(它背后的全部故事在这里:): …但已将“无”添加到枚举中,因为许多客户不会拥有/使用: public enum BeltPrinterType { None, ZebraQL220, ONiel // add more as needed } 编译器不允许我没有默认大小写(“并非所有代码路径都返回值”) “None”选项可能应该是默认情况,但如果None是printerChoice的当前值,则永远不应该调用工厂(当“None”是值时,启动滚动的GU
public enum BeltPrinterType
{
None,
ZebraQL220,
ONiel
// add more as needed
}
编译器不允许我没有默认大小写(“并非所有代码路径都返回值”)
“None”选项可能应该是默认情况,但如果None是printerChoice的当前值,则永远不应该调用工厂(当“None”是值时,启动滚动的GUI甚至不会显示),但是为了编译器的缘故,应该如何实现呢?我能不能什么都不退?或者我需要做一些“奇怪”的事情,比如:
在这些方法的末尾抛出一个
NotSupportedException
,不要返回null
如果工厂不允许使用None
选项,则抛出一个异常。如果
None
对工厂有效,则返回IBeltPrinter
的虚拟实现不要返回
null
我要尝试一下
这对你有用吗
public class BeltPrinterFactory : IBeltPrinterFactory
{
public IBeltPrinter NewBeltPrinter()
{
BeltPrinter item = new BeltPrinter();
switch (printerChoice)
{
case BeltPrinterType.ZebraQL220:
item.FunctionCall = ZebraCallback;
case BeltPrinterType.ONiel:
item.FunctionCall = ONielCallback;
default:
// do nothing;
}
return item;
}
}
您需要创建回调并重新设计您的IBeltPrinter
,但市长布隆伯格和O.J.辛普森应该能够理解这一点
要么这样,要么我真的不明白你在问什么。这并不奇怪,它被称为,IMO比处理异常或空值要好得多。工厂模式(在大多数情况下)已经过时,并被IoC和依赖注入所取代。@HighCore,是吗?我一定是错过了备忘录。@Moo Juice这些可怕的无休止的
开关(某物)
与最原始的DI形式相比根本不起作用。@HighCore:真是胡说八道。工厂模式不是DI的等价物,switch
也不是实现工厂的单一方法。
. . .
default:
return new None();
. . .
public class None : IBeltPrinter
{
public void PrintLabel(string price, string description, string barcode)
{
;// do nothing
}
}
public class BeltPrinterFactory : IBeltPrinterFactory
{
public IBeltPrinter NewBeltPrinter()
{
BeltPrinter item = new BeltPrinter();
switch (printerChoice)
{
case BeltPrinterType.ZebraQL220:
item.FunctionCall = ZebraCallback;
case BeltPrinterType.ONiel:
item.FunctionCall = ONielCallback;
default:
// do nothing;
}
return item;
}
}