为什么在尝试使用接口字典作为方法参数时,编译器不能从派生的 class 转换为它的接口?
Why can't the compiler convert from a derived class to it's interface when trying to use a Dictionary of interfaces as a method parameter?
我正在尝试将 Dictionary<string, Derived>
传递到需要 Dictionary<string, IBase>
的方法中。当我这样做时,编译器会抛出以下错误消息
cannot convert from Dictionary<string, Derived> to Dictionary<string, IBase>
下面是我正在尝试做的事情的简化版本。编译错误发生在我调用 Test(aDict);
的地方
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var aDict = new Dictionary<string, Derived>();
Test(aDict);
}
void Test(Dictionary<string, IBase> dict)
{}
}
public interface IBase
{}
public class Derived : IBase
{}
如果有人能告诉我如何在不出现异常的情况下执行此操作,或者解释为什么它不能在 c# 中完成,我将不胜感激。
假设它可以。还假设有 另一个 class、EvilDerived
实现了 IBase
。假设 Test
这样做了:
void Test(Dictionary<string, IBase> dict)
{
dict.Add("EvliKey", new EvilDerived());
}
Test
中的代码完全有效,但是传入的字典只能将 Derived
个对象作为其值,因此它不能将 EvilDerived
作为价值。那会发生什么?
你 可能 可以通过使 Test
通用并将值类型限制为 IBase
的(单一)实现来绕过它:
void Test<T>(Dictionary<string, T> dict) where T : IBase
{}
但是因为你没有展示你在做什么 Test
所以不可能知道这是否适合你。
我正在尝试将 Dictionary<string, Derived>
传递到需要 Dictionary<string, IBase>
的方法中。当我这样做时,编译器会抛出以下错误消息
cannot convert from Dictionary<string, Derived> to Dictionary<string, IBase>
下面是我正在尝试做的事情的简化版本。编译错误发生在我调用 Test(aDict);
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var aDict = new Dictionary<string, Derived>();
Test(aDict);
}
void Test(Dictionary<string, IBase> dict)
{}
}
public interface IBase
{}
public class Derived : IBase
{}
如果有人能告诉我如何在不出现异常的情况下执行此操作,或者解释为什么它不能在 c# 中完成,我将不胜感激。
假设它可以。还假设有 另一个 class、EvilDerived
实现了 IBase
。假设 Test
这样做了:
void Test(Dictionary<string, IBase> dict)
{
dict.Add("EvliKey", new EvilDerived());
}
Test
中的代码完全有效,但是传入的字典只能将 Derived
个对象作为其值,因此它不能将 EvilDerived
作为价值。那会发生什么?
你 可能 可以通过使 Test
通用并将值类型限制为 IBase
的(单一)实现来绕过它:
void Test<T>(Dictionary<string, T> dict) where T : IBase
{}
但是因为你没有展示你在做什么 Test
所以不可能知道这是否适合你。