为什么C#编译器不能推断FooExt.Multiply()
满足签名的事实Functions.Apply()
?我必须为代码指定一个单独的委托变量类型Func<Foo,int,int>
才能工作......但似乎类型推断应该处理这个问题.我错了吗?如果是这样,为什么?
编辑:收到的编译错误是:
FirstClassFunctions.Functions.Apply<T1,T2,TR>(T1, System.Func<T1,T2,TR>, T2)'
无法从用法中推断出方法的类型参数.尝试显式指定类型参数
namespace FirstClassFunctions {
public class Foo {
public int Value { get; set; }
public int Multiply(int j) {
return Value*j;
}
}
public static class FooExt {
public static int Multiply(Foo foo, int j) {
return foo.Multiply(j);
}
}
public static class Functions {
public static Func<TR> Apply<T1,T2,TR>( this T1 obj,
Func<T1,T2,TR> f, T2 val ) {
return () => f(obj, val);
}
}
public class Main …
Run Code Online (Sandbox Code Playgroud) 有没有更好的方法来编写这段代码而不使用goto
?这看起来很尴尬,但我想不出更好的方法.我需要能够执行一次重试尝试,但我不想复制任何代码.
public void Write(string body)
{
bool retry = false;
RetryPoint:
try
{
m_Outputfile.Write(body);
m_Outputfile.Flush();
}
catch (Exception)
{
if( retry )
throw;
// try to re-open the file...
m_Outputfile = new StreamWriter(m_Filepath, true);
retry = true;
goto RetryPoint;
}
}
Run Code Online (Sandbox Code Playgroud)