仿制药的问题C#继承 [英] C# inheritance in generics question

查看:148
本文介绍了仿制药的问题C#继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个接口:

public interface A { 
 void aMethod(); 
}


public interface B : A {
 void bMethod();
} 



后来我基本上使用这样的字典:

Later I'm basically using a dictionary like this:

Dictionary<int, A> dict = new Dictionary<int, B>();



C#是说我不能从右边转化为左边,即使我投它。有没有办法使用泛型在C#,使这个可以工作的方法吗?如果我让他们抽象类这似乎是确定,但我需要这些作为接口。

C# is saying I can't convert from the right to the left, even if I cast it. Is there a way to use generics in C# so that this can work? If I make them abstract classes it seems to be ok but I need these as interfaces.

推荐答案

您正在寻找的是特征什么是被称为仿制药方差(协方差和逆变)。有这个首发的.NET Framework 4,这里有一个有趣的帖子有限的支持:的通用协方差和孔特拉方差是如何实现在C#4.0

The feature you are looking for is what's referred to as generics variance (covariance and contravariance). There is limited support for this starting in .net framework 4. Here's an interesting post: How is Generic Covariance & Contra-variance Implemented in C# 4.0?

和这里的的MSDN条目泛型

这篇关于仿制药的问题C#继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆