工厂的基础上的typeof或者是 [英] Factory based on Typeof or is a
本文介绍了工厂的基础上的typeof或者是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是低于我想要返回基于另一个类的类型,派生类的代码更优雅的方式。
如果(option_为矩形)
{
modelInputs =新的Foo();
}
,否则如果(option_是圆)
{
modelInputs =新的酒吧();
}
,否则如果(option_是三角形)
{
modelInputs =新条2();
}
解决方案
的矩形,圆形和三角形实施IHasModelInput:
接口IHasModelInput
{
IModelInput GetModelInput();
}
那么你可以做
IModelInput modelInputs = option_.GetModelInput();
What's a more elegant way of having the code below where i want to return a derived class based on the type of another class.
if (option_ is Rectangle)
{
modelInputs = new Foo();
}
else if (option_ is Circle)
{
modelInputs = new Bar();
}
else if (option_ is Triangle)
{
modelInputs = new Bar2();
}
解决方案
Have Rectangle, Circle and Triangle implement IHasModelInput:
interface IHasModelInput
{
IModelInput GetModelInput();
}
then you can do
IModelInput modelInputs = option_.GetModelInput();
这篇关于工厂的基础上的typeof或者是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文