返回T的抽象方法的基类

时间:2017-11-17 20:33:28

标签: c#

我正在定义一个基类,它有一个返回类型T的方法。从中派生的类可以返回不同的类型。

public abstract class BaseTransport
{
    public abstract T Properties<T>();
}

public class Car : BaseTransport
{
    public override T Properties<T>()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport
{
    public override T Properties<T>()
    {
       return new BikeProperties();
    }
}

如果它有所不同,返回的BikeProperties和CarProperties都是从BaseProperties派生的。

这可能吗?只是试图强制执行方法...

1 个答案:

答案 0 :(得分:2)

您不需要泛型方法,您需要泛型类:

public abstract class BaseTransport<T> where T : BaseProperties
{
    public abstract T Properties();
}

public class Car : BaseTransport<CarProperties>
{
    public override CarProperties Properties()
    {
       return new CarProperties();
    }
}

public class Bike : BaseTransport<BikeProperties>
{
    public override BikeProperties Properties()
    {
       return new BikeProperties();
    }
}