无法通过委托

2023-09-04 13:07:06 作者:爱如柠檬滋味酸

我创建了一个函数,会从AS-只要它符合一个过滤器可以这么说用户控制台输入。

 公共委托TResult OutFunc<在T,TValue,出TResult>(T ARG1,出TValue ARG2);

公共静态牛逼PromptForInput< T>(字符串提示,OutFunc<字符串,T,布尔过滤器过滤)
{
    t值;
    做{Console.Write(提示); }
    而(过滤器(到Console.ReadLine(),超时值)!);
    返回值;
}
 

这个伟大的工程,当我打电话的方法,我做如下。它得到了一些来自用户只要解析到一个 INT 这是在范围(0-10)。

  INT NUM = PromptForInput(请输入一个整数:,
    委托(串ST,OUT INT结果)
    {返回int.TryParse(ST,出结果)及和放大器;结果&其中; = 10&安培;&安培;结果> = 0; });
 

我希望能够重复使用常用的过滤器。在我的程序多的地方,我希望得到来自用户的 INT 输入,所以我已经分离出该逻辑,并提出,在自己的功能。

 私人布尔IntFilter(字符串ST,OUT INT结果)
{
    返回int.TryParse(ST,出结果)及和放大器;结果&其中; = 10&安培;&安培;结果> = 0;
}
 
职场干货分享 委托书模板

现在,当我试图做到这一点我得到一个错误:

  INT NUM = PromptForInput(请输入一个整数:IntFilter);
 

  

有关法PromptForInput(字符串,OutFunc)的类型参数不能从使用推断。请尝试显式指定类型参数。

我怎么能明确指定在这种情况下,类型参数?

解决方案

您有一个通用的功能,所以需要声明的类型:

  INT NUM = PromptForInput< INT>(请输入一个整数: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.

相关推荐