制作这样的通用方法:
public void DoSomething<T>(IDictionary<int, T> dictionary) where T : B
Run Code Online (Sandbox Code Playgroud)
或者类似地使控件本身通用(这会给你的设计师带来问题,但......)
public class MyControl<T> where T : B
{
private IDictionary<int, T> dictionary;
...
}
Run Code Online (Sandbox Code Playgroud)
由于通用不变性,您需要这样做.即使在C#4(支持一些方差)中,这也是不变的:字典使用输入和输出的值.
想象一下,你可以转换Dictionary<int, X>为Dictionary<int, B>.然后你就可以写:
dictionary[0] = new B();
Run Code Online (Sandbox Code Playgroud)
......这显然不适用于字典,因为它不是X......