【发布时间】:2013-01-27 12:17:48
【问题描述】:
我有一个这样的通用函数:
private LOCAL_TYPE RemoteToLocal<LOCAL_TYPE>(RemoteObjectBaseType remoteObject)
where LOCAL_TYPE: EntityBase
{
Type t = typeof(LOCAL_TYPE);
if (t == typeof(FavoritePlace))
{
return new FavoritePlace(remoteObject as RemotePlaceType1);
}
}
EntityBase 是非抽象类。 FavoritePlace 类继承自 EntityBase。
但是,我收到一个错误:
无法将类型 Common.Model.FavoritePlace 隐式转换为“LOCAL_TYPE”。
这让我想知道:FavoritePlace 是 EntityBase 的子代,而 LOCAL_TYPE 被限制为 EntityBase 类型。为什么不能发生转换?我可能在这里遗漏了一些重要的东西。
编辑:好的,根据当前的答案和一些实验,我找到了另一种解决方法,即进行以下转换:
if (t == typeof(FavoritePlace))
{
return (LOCAL_TYPE)(EntityBase)new FavoritePlace(remoteObject);
}
现在编译器很高兴。但我只是想知道,如果从编译器的角度来看这种转换是可能的,为什么不能直接转换为 LOCAL_TYPE 呢? 不是可转换为关系传递的吗?
【问题讨论】:
-
Derived1 继承自 Base,Derived2 继承自 Base。那么,你能把Derived1转换成Derived2吗?在您的示例中,Derived2 是 LOCAL_TYPE,Derived1 是 FavoritePlace 并且 Base 是 EntityBase.
-
强制转换运算符实际上可以执行一些非常不同的操作。它可以安全地转换为基本类型(
FavoritePlace→EntityBase),也可以转换为派生类型(EntityBase→LOCAL_TYPE,这可能会引发异常),但它不能从一个转换一步子类化为另一个。
标签: c# generics type-conversion .net-4.5