我有以下高阶函数:
public static Func<T, bool> Not<T>(Func<T, bool> otherFunc)
{
return arg => !otherFunc(arg);
}
并尝试这样调用它:
var isValidStr = LinqUtils.Not(string.IsNullOrWhiteSpace);
编译器给我“无法从用法中推断出类型参数”错误。 但以下工作:
var isValidStr = LinqUtils.Not((string s) => string.IsNullOrWhiteSpace(s));
我想知道有什么区别?
string.IsNullOrWhiteSpace
已经是具有完全相同签名的非重载函数。
如评论中所述,以下内容也有效,但仍未解释为什么类型推断在这种情况下失败:
var isValidStr = LinqUtils.Not<string>(string.IsNullOrWhiteSpace);
最佳答案
Eric Lippert 在他的博客 here 上回答了您正在处理的问题的详细信息.
基本上,正如“David B”在您的评论中所说,“IsNullOrWhiteSpace 是一个方法组。该方法组今天只有一个参与成员,但将来可能会有更多。”
关于c# - 无法从高阶函数的用法中推断出类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11001673/