简体   繁体   中英

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM