小编Clu*_*der的帖子

为什么C#编译器不会自动推断出此代码中的类型?

为什么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)

.net c# generics type-inference c#-3.0

11
推荐指数
1
解决办法
490
查看次数

在没有goto的情况下编写重试逻辑的更好方法

有没有更好的方法来编写这段代码而不使用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)

.net c# goto

7
推荐指数
3
解决办法
6334
查看次数

标签 统计

.net ×2

c# ×2

c#-3.0 ×1

generics ×1

goto ×1

type-inference ×1