c# - 不能通过委托(delegate)

标签 c# .net 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;
}

当我按照下面的方式调用该方法时,效果很好。只要它解析为 (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/

相关文章:

jquery - 有没有更好的方法在 jQuery Mobile 中附加到 pageshow?

c# - UITextView - InsertText 不会自动更正或自动大写

c# - 无法在 Visual Studio 中放置行号

c# - 使用 C# .NET 查询本地比特币区 block 链

c# - 仅限于包含特定属性的对象的扩展方法

ios - 类方法单例对象可以响应委托(delegate)调用吗?

design-patterns - 更改 haxe 对象的 "this"范围。可能的?

c# - Visual Studio 中的 Entity Framework : database is not created with DbContext base constructor

c# - 复制游戏对象的所有变换值?

c# - 将 C# Console.Write* 与 AWS Lambda 结合使用