我正在定义一个基类,它有一个返回类型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派生的。
这可能吗?只是试图强制执行方法...
答案 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();
}
}