如何在select语句中传递要运行的参数中的anon函数?
public IEnumerable<string> Tokenize(Func<string> tokenFunc = null)
{
IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
if (tokenFunc != null)
{
tokens = tokens.Select(tokenFunc);
}
}
我收到错误:
方法的类型参数&#39; Enumerable.Select(IEnumerable,Func)&#39;无法从使用中推断出来。尝试明确指定类型参数
我做错了什么?
我想这样称呼它:
MyViewObj.Tokenize( (x) => { if(x=='1') return 1; else return 0; });
答案 0 :(得分:2)
问题在于您的tokenFunc
应该是Func<TSource, TResult>
类型,而您提供Func<TResult>
。
天真地看着你如何称呼它,它应该成为:
public IEnumerable<string> Tokenize(Func<string, int> tokenFunc = null)
{
IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
if (tokenFunc != null)
{
tokens = tokens.Select(tokenFunc);
}
}
但是,这当然会失败,因为您尝试将结果分配给IEnumerable<string>
,但实际上正在返回IEnumerable<int>
要使所有内容协同工作,您需要将内容更改为Func<string, string>
并在通话中返回"0"
或"1"
而不是0
或1
:
public IEnumerable<string> Tokenize(Func<string, string> tokenFunc = null)
{
IEnumerable<string> tokens = Regex.Split(INPUT, @"(\d+|&|\||\(|\))").Where(x => string.IsNullOrEmpty(x) == false);
if (tokenFunc != null)
{
tokens = tokens.Select(tokenFunc);
}
}
将调用代码更改为:
MyViewObj.Tokenize( (x) => { if(x=="1") return "1"; else return "0"; });
答案 1 :(得分:0)
因为您需要一个Func将字符串作为输入并返回您的返回类型:
Func<string,int> tokenFunc