不能通过委托 [英] Can't pass delegate

查看:35
本文介绍了不能通过委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个函数,它可以从用户那里获取控制台输入,只要它适合过滤器就可以了.

public delegate TResult OutFunc(T arg1, out TValue arg2);public static T PromptForInput(string prompt, OutFunc filter){T值;做 { Console.Write(prompt);}while (!filter(Console.ReadLine(), out value));返回值;}

当我像下面那样调用方法时,这很有效.只要它解析为一个范围为 (0-10) 的 int,它就会从用户那里获取一个数字.

int num = PromptForInput("请输入一个整数:",委托(字符串 st,输出 int 结果){ return int.TryParse(st, out result) &&结果 <= 10 &&结果>= 0;});

我希望能够重复使用常用过滤器.在我的程序的多个地方,我想从用户那里得到一个 int 输入,所以我已经分离了它的逻辑,并将其放在自己的函数中.

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

现在,当我尝试执行此操作时出现错误:

int num = PromptForInput("请输入一个整数:", IntFilter);

<块引用>

无法从用法推断方法PromptForInput(string, OutFunc)"的类型参数.尝试明确指定类型参数.

在这种情况下如何明确指定类型参数?

解决方案

你有一个泛型函数,所以需要声明类型:

int num = PromptForInput("请输入一个整数:", IntFilter);

编译器只是说它自己无法弄清楚,需要显式声明它.

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.

这篇关于不能通过委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆