6

Can not pass delegate

 2 years ago
source link: https://www.codesd.com/item/can-not-pass-delegate.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Can not pass delegate

advertisements

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK