[英]base class with abstract method returning T
I am defining a base class that has a method that returns type T. The classes the derive from this can return different types. 我正在定义一个具有返回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();
}
}
If it makes a difference the return BikeProperties and CarProperties are both derived from BaseProperties. 如果有所不同,则返回的BikeProperties和CarProperty都从BaseProperties派生。
Is this possible to do? 这可能吗? Just trying to enforce the implementation of a method... 只是试图强制执行方法...
You don't want generic methods, you want a generic class: 您不需要通用方法,需要通用类:
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.