我创建了一个从用户获取控制台输入的功能,只要它适合过滤器即可.
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, …Run Code Online (Sandbox Code Playgroud)