[英]abstract class property from Factory C#
Consider the following abstract class :考虑以下抽象类:
public abstract class BuildingBase
{
public abstract BuildingType Type { get; }
}
this class is inherited by two classes :这个类由两个类继承:
public class Appartment : BuildingBase
{
public override BuildingType Type => BuildingType.Appartment;
}
public class House: BuildingBase
{
public override BuildingType Type => BuildingType.House;
}
I have a factory that should 'build' based on the type passed :我有一个工厂应该根据传递的类型“构建”:
public class Builder {
public BuildingBase Build(BuildingType type) {
// how to get this implemented without if / else .. case when ... etc
}
}
I'd use generics in this case, like this:在这种情况下,我会使用泛型,如下所示:
public class Builder
{
public TBuildingBase Build<TBuildingType>()
where TBuildingBase : BuildingBase, new()
{
var result = new TBuildingBase();
...
}
}
But I'm not sure if you require the Enum
as an input.但我不确定您是否需要Enum
作为输入。 I'm afraid that if you do want to stick with it, your choices are either an if-else construct, a constructor map like @Selvin mentioned, or using reflection (ugh).恐怕如果您确实想坚持下去,您的选择要么是 if-else 构造,要么是 @Selvin 提到的构造函数映射,要么是使用反射(呃)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.