ada*_*m.k 1 .net c# generics dictionary .net-core
我有一个这样的方法:
public void SomeMethod(Dictionary<IFoo, IBar> myDict) {}
Run Code Online (Sandbox Code Playgroud)
我有两个继承自 IFoo 和 IBar 的类:
public class FooClass : IFoo {}
public class BarClass : IBar {}
Run Code Online (Sandbox Code Playgroud)
我正在尝试将我的方法与如下字典一起使用:
Dictionary<FooClass, BarClass> myDict = DeserializeFromJson();
SomeMethod(myDict);
Run Code Online (Sandbox Code Playgroud)
但我收到编译错误
参数不能从 ... 转换为 ...”。
有人可以解释为什么这种转换无效吗?
请参阅有关从转换这个问题List<Dog>到List<Animal>了,为什么你不能直接这样做。这是特定于字典的解释,想象一下你可以这样做:
// here, myDict is of type Dictionary<Foo, Bar>, as we are outside SomeMethod
// suppose myDict is empty initially
SomeMethod(myDict);
Run Code Online (Sandbox Code Playgroud)
然后SomeMethod可以这样做:
// here, myDict is of type Dictionary<IFoo, IBar>, as we are inside SomeMethod
myDict.Add[new AnotherClass1(), new AnotherClass2());
Run Code Online (Sandbox Code Playgroud)
在哪里
class AnotherClass1: IFoo {}
class AnotherClass2: IBar {}
Run Code Online (Sandbox Code Playgroud)
之后SomeMethod的回报,你这样做:
// here, myDict is Dictionary<Foo, Bar> again, we are outside SomeMethod
Bar firstValue = myDict.Values.First();
Run Code Online (Sandbox Code Playgroud)
等等...firstValue应该是类型AnotherClass2!
看到问题了吗?
而不是创造一个Dictionary<IFoo, IBar>具有相同价值观的新事物,
Dictionary<IFoo, IBar> newDict = myDict.ToDictionary(x => x.Key, y => y.Value);
Run Code Online (Sandbox Code Playgroud)
这可能需要一些时间(并且对字典的修改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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34 次 |
| 最近记录: |