0
值为什么没有可能通过使用字典,一个接口作为方法参数
Dictionary<string, PinkLady>()
到我Supply(Dictionary<string, IApple> apples)
方法?
public interface IApple { }
public class PinkLady : IApple { }
public void Supply(Dictionary<string, IApple> apples) { }
public void TestMethod()
{
//Working
Supply(new Dictionary<string, IApple>());
//Not working
Supply(new Dictionary<string, PinkLady>());
}
我总是得到一个错误:
converting from Dictionary into Dictionary not possible. PinkLady does not match expected type IApple.
请仔细阅读本https://stackoverflow.com/questions/2662369/covariance-and-contravariance-real-世界范例 –
您要求它确保'Dictionary'的一个实例在所有情况下都可以安全地视为'Dictionary '。但'Dictionary '保证你可以调用'Add(myCortland)','Dictionary '保证你不能。 –