【发布时间】:2016-12-02 22:35:10
【问题描述】:
让我们从以下分类开始
public abstract class Automobile { }
public class Automobile<T> : Automobile where T : Automobile { }
public class Car : Automobile<Car> { }
public class Truck : Automobile<Truck> { }
public class SmartAutomobile<T> : Automobile<T>
{
public T MyAutomobile { get; set; }
public SmartAutomobile(SmartTechnology smart)
{
// Cannot implicitly convert Automobile to T
this.MyAutomobile = AutomobileFromSmart(typeof(T), smart);
}
public static Automobile AutomobileFromSmart(Type type, SmartTechnology smart)
{
if (type == typeof(Car))
return new Car { /* ... */ };
else
throw new NotImplementedException("Car type " + type.FullName + " not recognized");
}
}
public class SmartTechnology { }
从评论中可以看出,编译器说它无法在SmartAutomobile<T> 的构造函数中将Automobile 转换为T。怎么会这样?编译器应该知道 T,由于 Automobile<T> 中的约束,是 Automobile。
如果我尝试显式转换它
this.MyAutomobile = AutomobileFromSmart(typeof(T), smart) as T;
我得到编译器错误
类型参数“T”不能与“as”运算符一起使用,因为它没有类类型约束,也没有“类”约束
现在,如果我还在SmartAutomobile<T> 中定义where 约束
public class SmartAutomobile<T> : Automobile<T> where T : Automobile
编译器没有显示任何错误
但如果我删除显式演员:
this.MyAutomobile = AutomobileFromSmart(typeof(T), smart);
Cannot implicitly convert Automobile to T错误再次出现。
编译器怎么可能没有意识到where 约束强制T 成为Automobile?
【问题讨论】:
-
您没有将其限制为
class。 -
既然你想投它实际上投它。你不是在表演。
-
顺便说一句,C#有编译器而不是解释器
标签: c#