泛型和強(qiáng)制轉(zhuǎn)換 - 不能將繼承的類強(qiáng)制轉(zhuǎn)換為基類我知道這是舊的,但我仍然不太了解這些問題。任何人都可以告訴我為什么以下不起作用(拋出runtime關(guān)于投射的例外)?public abstract class EntityBase { }public class MyEntity : EntityBase { }public abstract class RepositoryBase<T> where T : EntityBase { }public class MyEntityRepository : RepositoryBase<MyEntity> { }而現(xiàn)在的鑄造線:MyEntityRepository myEntityRepo = GetMyEntityRepo(); // whateverRepositoryBase<EntityBase> baseRepo = (RepositoryBase<EntityBase>)myEntityRepo;那么,任何人都可以解釋這是如何無效的?而且,我沒有心情去解釋 - 是否有一行代碼我可以用來實(shí)際進(jìn)行演員表演?
3 回答

嚕嚕噠
TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
這需要協(xié)方差或逆變,其支持僅限于.Net,不能用于抽象類。您可以在接口上使用方差,因此您的問題的可能解決方案是創(chuàng)建一個(gè)IRepository,您可以使用它來代替抽象類。
public interface IRepository<out T> where T : EntityBase { //or "in" depending on the items. } public abstract class RepositoryBase<T> : IRepository<T> where T : EntityBase { } public class MyEntityRepository : RepositoryBase<MyEntity> { } ... IRepository<EntityBase> baseRepo = (IRepository<EntityBase>)myEntityRepo;
- 3 回答
- 0 關(guān)注
- 717 瀏覽
添加回答
舉報(bào)
0/150
提交
取消