I have the following higher-order function:

public static Func<T, bool> Not<T>(Func<T, bool> otherFunc)
{
    return arg => !otherFunc(arg);
}

And trying to call it like that:

var isValidStr = LinqUtils.Not(string.IsNullOrWhiteSpace);

Compiler gives me "type arguments cannot be inferred from the usage" error. But the following works:

var isValidStr = LinqUtils.Not((string s) => string.IsNullOrWhiteSpace(s));

I wonder what the difference is? string.IsNullOrWhiteSpace is already a non-overloaded function with the exactly same signature.

As mentioned in comments, the following also works and still doesn't explain why type inference fails in this case:

var isValidStr = LinqUtils.Not<string>(string.IsNullOrWhiteSpace);
有帮助吗?

解决方案

The details of the issue you are dealing with are answered by Eric Lippert on his blog, here.

Basically, as "David B" said in your comments, "IsNullOrWhiteSpace is a method group. The method group only has one participating member today, but it could get more in the future."

其他提示

This works:

var isValidStr = Not<string>(string.IsNullOrWhiteSpace);

Although, It seems like the compiler should have enough information to infer the type parameters here - and this shouldn't be required...

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top