[英]base class with abstract method returning T
我正在定义一个具有返回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和CarProperty都从BaseProperties派生。
这可能吗? 只是试图强制执行方法...
您不需要通用方法,需要通用类:
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.