【发布时间】:2010-08-20 07:06:11
【问题描述】:
我知道这已经过时了,但我仍然不太了解这些问题。谁能告诉我为什么以下方法不起作用(抛出关于投射的runtime 异常)?
public abstract class EntityBase { }
public class MyEntity : EntityBase { }
public abstract class RepositoryBase<T> where T : EntityBase { }
public class MyEntityRepository : RepositoryBase<MyEntity> { }
现在是铸造线:
MyEntityRepository myEntityRepo = GetMyEntityRepo(); // whatever
RepositoryBase<EntityBase> baseRepo = (RepositoryBase<EntityBase>)myEntityRepo;
那么,任何人都可以解释这是无效的吗?而且,我没有心情解释 - 有没有一行代码我可以用来实际执行此转换?
【问题讨论】:
-
感谢大家的回答。简而言之 - 我现在使用基本接口 (RepositoryBase
: IRepository) 解决了这个问题。结果我只需要在我得到的实例上执行函数,让类本身处理其他事情。