我有一些问题围绕着调用泛型方法。在下面的示例中,当我从基类中调用ServiceCar
时,在经销商中定义该方法时出现错误:泛型类型约束似乎没有约束任何东西
定义1:ServiceCar<C>(C carToService) where C : Car<C>
。
但是,当该方法在经销商被定义为我没有得到在基类中的错误:
定义2:ServiceCar<C>(Car<C> carToService) where C : Car<C>
public abstract class Car<T> where T: Car<T>
{
public bool isServiced;
public string serviceMessage;
public virtual void SendToService()
{
Dealer.ServiceCar<T>(this); // error here when Definition 1 used
serviceMessage = "Your car is clean.";
}
}
public class Ford: Car<Ford>
{
public override void SendToService()
{
Dealer.ServiceCar<Ford>(this);
serviceMessage = "Your Ford is clean.";
}
}
public class Dealer
{
// When the parameter is defined as C (as commented below) an error occurs
// When the parameter is defined as Car<C> there are no errors
// public static void ServiceCar<C>(C carToService) where C : Car<C>
public static void ServiceCar<C>(Car<C> carToService) where C : Car<C>
{
carToService.isServiced = true;
}
}
我的困惑是,微软says“凡T:意味着类型参数必须是或从指定的基类派生的“在定义1(不编译)的情况下,C是Car<C>
。那么为什么不是类型约束参数帮助我。我得到的错误读取“...不能从Car<T>
转换到T”我缺少什么?
我知道这不是一个理想的样本,有更好的方法来做到这一点。我只是试图找到一种方法来从基类和继承类调用相同的泛型方法。 –
哦,好的。你可以试试这个,然后'public static void ServiceCar(C carToService)where C:Car'然后从你的基类中移除泛型定义。 –
Jay