【发布时间】:2013-11-09 21:35:31
【问题描述】:
我在调用泛型方法时遇到了一些问题。在下面的示例中,当我从基类调用 ServiceCar 时,如果该方法在 Dealer 中定义为:
定义 1:ServiceCar<C>(C carToService) where C : Car<C>。
但是当该方法在 Dealer 中定义为时,我在基类中没有收到错误:
定义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;
}
}
我的困惑是 Microsoft says 认为“其中 T:表示类型参数必须是或派生自指定的基类” 好吧,在定义 1(不编译)的情况下,C 是 Car<C>。那么为什么类型约束参数不能帮助我。我收到的错误是“...无法从 Car<T> 转换为 T”我错过了什么?
【问题讨论】: