我有一个简单的工厂方法,它根据所提供的泛型类型参数提供具体的实现实例。如果具体类继承自具有类型参数的公共(public)抽象基类,我将无法强制转换它们。编译器告诉我 Error 2 Cannot convert type 'Car' to 'VehicleBase<T>'
.如果我将抽象类替换为具有相同类型参数的接口(interface),或者如果我从抽象类中删除泛型类型参数,它就可以正常工作。
interface IWheel
{
}
class CarWheel : IWheel
{
}
abstract class VehicleBase<T>
{
}
class Car : VehicleBase<CarWheel>
{
}
class VehicleFactory
{
public static VehicleBase<T> GetNew<T>()
{
if (typeof(T) == typeof(CarWheel))
{
return (VehicleBase<T>)new Car();
}
else
{
throw new NotSupportedException();
}
}
}
编译失败 (VehicleBase<T>)new Car()
.这是编译器缺陷,还是故意设计决定以不同方式处理具有类型参数的抽象类和接口(interface)?
作为一种解决方法,我总是可以让抽象类实现一个接口(interface)并将其用作我的工厂方法的返回值,但我仍然想知道为什么会发生这种行为。
最佳答案
这不是可证明的,因为通用代码需要为所有 可能工作(使用相同的 IL)T
,没有什么可说的Car : VehicleBase<float>
, 例如。编译器不会过度分析 if
的事实检查母 pig T
是CarWheel
- 静态检查器分开处理每个语句,它不会尝试理解条件的因果关系。
强制转换为 object
在中间:
return (VehicleBase<T>)(object)new Car();
但是!您的方法并不是真正的“通用”方法。
关于c# - 无法将派生类型转换为具有类型参数的基抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11201784/