I've created a function that gets console input from the user as-long as it fits a filter so to speak.

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;
}

This works great when I call the method as I do below. which gets a number from the user as long as it parses to an int which is in the range of (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; } );

I want to be able to re-use common filters. In multiple places in my program I want to get an int input from the user, so I've separated out the logic for that, and put that in its own function.

private bool IntFilter(string st, out int result)
{
    return int.TryParse(st, out result) && result <= 10 && result >= 0;
}

Now I get an error when I attempt to do this:

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.

How can I explicitly specify the type arguments in this case?

有帮助吗?

解决方案

You have a generic function, and so need to declare the type:

int num = PromptForInput<int>("Please input an integer: ", IntFilter);

The compiler is just saying it can't figure that out on it's own and needs it declared explicitly.

其他提示

Thanks to LordTakkera's answer I was able to also find this works as-well

int num = PromptForInput("Please input an integer: ", new OutFunc<string, int, bool>(IntFilter));

The compiler actually does this implicitly when compiling as long as you explicitly specify PromptForInput<int>. Though, I don't understand why the compiler can't figure this out implicitly.

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