字典用Func键为重点 [英] Dictionary with Func as key
问题描述
我想知道,如果这是关键的一个字典一个理智的选择吗?我想要做的是使用一个表达式作为字典的关键,是这样的:
I am wondering if this is a sane choice of key for a dictionary? What I want to do is use an expression as the key in a dictionary, something like:
var map3 = new Dictionary<Func<int, bool>, int>();
map3.Add((x) => x % 2 == 0, 1);
map3.Add((x) => x % 10 == 0, 2);
// ...
var key = map3.Keys.SingleOrDefault(f => f(2));
// key = (x) => x % 2
// map3[key] = 1
这个想法是这是一比有大的if-else或switch语句更清洁的方式。
The idea being this is a cleaner way than having big if-else or switch statements.
这是否有道理?它是否行得通呢?是否有一个更简单的方法?
Does this make sense? Will it work? Is there an simpler way?
推荐答案
没有,C#构造每当一个lambda使用,所以你不会成为一个新的委托实例能够使用它作为一个一致的密钥。例如:
No, C# constructs a new delegate instance whenever a lambda is used so you wouldn't be able to use it as a consistent key. Example:
Func<int, int> f = x => x*x + 1;
Func<int, int> g = x => x*x + 1;
Console.WriteLine(f.Equals(g)); // prints False
这会然后进行使用的尴尬作为字典的键,除非你有一些其他的方式来,总是得到相同的实例
This would then make usage awkward as a dictionary key unless you had some other way to always obtain the same instance.
编辑:
埃里克利珀的回答的here 表示该编译器的允许的检测lambda表达式是相同的(尽管它通常没有)。无论哪种方式,一个lambda /委托使得一个键一个糟糕的选择。
Eric Lippert's answer here indicates that the compiler is allowed to detect the lambdas are the same (although it typically does not). Either way a lambda/delegate makes a poor choice for a key.
这篇关于字典用Func键为重点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!