【发布时间】:2015-10-15 10:34:47
【问题描述】:
我知道编译器可以从 lambda 表达式转换为 Predicate。
例如:
Predicate<int> p = x => true;
很好。
但是当我想创建一个包含谓词的元组时。 我试过这样做(简化版):
Tuple<Predicate<int>> t;
t = Tuple.Create(x => true);
我得到了编译错误:
方法“System.Tuple.Create(T1)”的类型参数无法从用法中推断出来。尝试明确指定类型参数。
我的问题是这是什么错误,这里的歧义在哪里?
(我知道我可以通过强制转换来修复它:t = Tuple.Create((Predicate<int>)(x => true));
但我想了解为什么第一种方法不好,而且我不想进行强制转换以节省打字:)
【问题讨论】:
-
Tuple.Create 与前面声明的
t无关。所以编译器无法推断 x 的类型。 -
t = Tuple.Create<Predicate<int>>(x => true);会工作。您必须以某种方式指定类型。只是x => true是模棱两可的定义。 -
或者自己写工厂方法:
Tuple<Predicate<int>> CreateTuple(Predicate<int> predicate) { return Tuple.Create(predicate); } -
只是为了让你清楚。这将工作
t = Tuple.Create((Predicate<int>) (x => true));。为什么?因为您已将x => true转换为已知类型Predicate<int>,并且您必须知道x => true对编译器有数千种含义。无论如何,因为Tuple.Create是通用类型,您可以指定类型而不是强制转换,这更好并在答案中进行了解释。
标签: c# lambda delegates tuples predicate