有效地获取IReadOnlyDictionary< int,Animals>摘自Dictionary< int,Fleas> [英] Efficiently Obtain IReadOnlyDictionary<int, Animals> from Dictionary<int, Fleas>
问题描述
public class Flea : Animals {...}
var fleas = new Dictionary<int, Flea>();
public IReadOnlyDictionary<string, Animal> Animals => fleas.ToDictionary(pair => pair.Key, pair => (Animal)pair.Value);
Q 是否有更有效的方法获取动物
来自跳蚤
?
Q Is there a more efficient way to obtain Animals
from fleas
?
推荐答案
.NET在接口,委托,泛型类型和数组中支持协方差。接口或类型必须使用 out
关键字来指定其协变。
.NET supports covariance in interfaces, delegates, generic types and arrays. The interface or type has to specify it's covariant though with the out
keyword.
您可以编写
IEnumerable<Animal> animals=new List<Flea>();
或
var dict=new Dictionary<int,Flea>{
[1]=new Flea()
};
IEnumerable<Animal> animals=dict.Values;
之所以有效,是因为 Dictionary.Values
返回一个 IEnumerable< Flea>
和 IEnumerable 是协变的-其定义为 IEnumerable< out T>
。
This works because Dictionary.Values
returns an IEnumerable<Flea>
and IEnumerable is covariant - its definition is IEnumerable<out T>
.
KeyValuePair 虽然不是协变的,这意味着使用它的类如 IDictionary< TKey,TValue>
和 IReadOnlyDictionary< TKey,TValue>
也不是。
KeyValuePair though isn't covariant which means that the classes that use it like IDictionary<TKey,TValue>
and IReadOnlyDictionary<TKey,TValue>
aren't either. This was intentional.
由于您只需要从该词典中读取,因此可以使用委托创建访问器方法,或者在C#7中然后是局部函数您可以将该函数传递给期望 Func< TKey,TValue>
的方法,并使用它从字典中读取值。
Since you only need to read from that dictionary, you can create an accessor method using a delegate or, in C# 7 and later, a local function. You can pass that function to methods that expect a Func<TKey,TValue>
and use it to read values from the dictionary.
如果您有一种方法需要基于密钥的访问,请说:
If you have a method that needs key-based access, let's say :
void Process(Func<int,Animal> reader)
{
var value=reader(1);
}
在C#7中,您可以编写:
In C# 7 you can write :
var dict =...
Animal get(int key)=>dict[key];
Process(get);
通过使用变量捕获来访问字典,这有点作弊。
This cheats a bit, by using variable capture to access the dictionary.
在C#7之前,您将使用委托:
Before C# 7 you'd use a delegate :
Func<int,Animal> get= key=>dict[key];
Process(get);
这似乎很奇怪,但是 LINQ 本身就是这样工作的谓词和委托,而不是接口和包装。
This may seem strange, but that's how LINQ itself works, by using predicates and delegates instead of interfaces and wrappers.
这篇关于有效地获取IReadOnlyDictionary< int,Animals>摘自Dictionary< int,Fleas>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!