c#-泛型字典键值继承问题

c#

我有一个这样的方法:

public void SomeMethod(Dictionary<IFoo, IBar> myDict) {}

我有两个继承自 IFoo 和 IBar 的类:

public class FooClass : IFoo {}
public class BarClass : IBar {}

我正在尝试将我的方法与如下字典一起使用:

Dictionary<FooClass, BarClass> myDict = DeserializeFromJson();
SomeMethod(myDict);

但我收到编译错误

参数不能从 ... 转换为 ...”。

有人可以解释为什么这种转换无效吗?

回答

请参阅有关从转换这个问题List<Dog>List<Animal>,为什么你不能直接这样做。这是特定于字典的解释,想象一下你可以这样做:

// here, myDict is of type Dictionary<Foo, Bar>, as we are outside SomeMethod
// suppose myDict is empty initially
SomeMethod(myDict);

然后SomeMethod可以这样做:

// here, myDict is of type Dictionary<IFoo, IBar>, as we are inside SomeMethod
myDict.Add[new AnotherClass1(), new AnotherClass2());

在哪里

class AnotherClass1: IFoo {}
class AnotherClass2: IBar {}

之后SomeMethod的回报,你这样做:

// here, myDict is Dictionary<Foo, Bar> again, we are outside SomeMethod
Bar firstValue = myDict.Values.First();

等等...firstValue应该是类型AnotherClass2

看到问题了吗?

而不是创造一个Dictionary<IFoo, IBar>具有相同价值观的新事物,

Dictionary<IFoo, IBar> newDict = myDict.ToDictionary(x => x.Key, y => y.Value);

这可能需要一些时间(并且对字典的修改SomeMethod不会反映不是原始字典),您还可以使SomeMethod通用:

public void SomeMethod<TFoo, TBar>(Dictionary< TFoo, TBar> myDict) 
    where TFoo: IFoo
    where TBar: IBar 
{
    // the method can be implemented the same way as before
}


以上是c#-泛型字典键值继承问题的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>