Ben*_*dgi 3 .net c# delegates anonymous-function
我创建了一个从用户获取控制台输入的功能,只要它适合过滤器即可.
public delegate TResult OutFunc<in T, TValue, out TResult>(T arg1, out TValue arg2);
public static T PromptForInput<T>(string prompt, OutFunc<string, T, bool> filter)
{
T value;
do { Console.Write(prompt); }
while (!filter(Console.ReadLine(), out value));
return value;
}
Run Code Online (Sandbox Code Playgroud)
当我像下面这样调用方法时,这很有效.只要它解析到int(0-10)范围内的数字,它就从用户那里得到一个数字.
int num = PromptForInput("Please input an integer: ",
delegate(string st, out int result)
{ return int.TryParse(st, out result) && result <= 10 && result >= 0; } );
Run Code Online (Sandbox Code Playgroud)
我希望能够重复使用常见的过滤器.在我的程序中的多个地方,我想int从用户那里得到一个输入,所以我已经分离了它的逻辑,并把它放在它自己的函数中.
private bool IntFilter(string st, out int result)
{
return int.TryParse(st, out result) && result <= 10 && result >= 0;
}
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试这样做时,我收到一个错误:
int num = PromptForInput("Please input an integer: ", IntFilter);
Run Code Online (Sandbox Code Playgroud)
无法从用法中推断出方法'PromptForInput(string,OutFunc)'的类型参数.尝试显式指定类型参数.
在这种情况下,如何显式指定类型参数?
你有一个泛型函数,所以需要声明类型:
int num = PromptForInput<int>("Please input an integer: ", IntFilter);
Run Code Online (Sandbox Code Playgroud)
编译器只是说它不能自己解决它并且需要它明确声明.