我已经创建了一个函数,可以从用户那里获取控制台输入,可以这么说,只要它符合过滤器即可。
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;
}
当我按照下面的方式调用该方法时,效果很好。只要它解析为 (0-10) 范围内的 int
,它就会从用户那里获取一个数字。
int num = PromptForInput("Please input an integer: ",
delegate(string st, out int result)
{ return int.TryParse(st, out result) && result <= 10 && result >= 0; } );
我希望能够重复使用常用过滤器。在我的程序的多个地方,我想从用户那里得到一个 int
输入,所以我已经分离出它的逻辑,并将它放在它自己的函数中。
private bool IntFilter(string st, out int result)
{
return int.TryParse(st, out result) && result <= 10 && result >= 0;
}
现在当我尝试这样做时出现错误:
int num = PromptForInput("Please input an integer: ", IntFilter);
The type arguments for method 'PromptForInput(string, OutFunc)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
在这种情况下如何显式指定类型参数?
最佳答案
你有一个泛型函数,所以需要声明类型:
int num = PromptForInput<int>("Please input an integer: ", IntFilter);
编译器只是说它无法自行解决,需要明确声明。
关于c# - 不能通过委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22386511/