【问题标题】:Both Action and Func<T> without explicit castingAction 和 Func<T> 都没有显式转换
【发布时间】:2012-07-10 18:37:24
【问题描述】:

我有一个类必须接收方法才能调用它们以及执行其他执行。这些方法必须多次使用,并且适用于许多不同的用户,所以越简单越好。

为了解决这个问题,我有两种方法:

    void Receive(Action func)
    {
        // Do some things.
        func();
    }

    T Receive<T>(Func<T> func)
    {
        // Do some things.
        return func();
    }

(实际上我有 34 种方法可以接收定义的任何不同的 Action 或 Func。)

然后,我希望能够将任何方法作为参数传递给 Receive 函数,以便能够执行以下操作:

    void Test()
    {
        Receive(A);
        Receive(B);
    }

    void A()
    {
    }

    int B()
    {
        return 0;
    }

就像这样,它在 Receive(B) 中给了我一个错误:

The call is ambiguous between the following methods or properties: 'Class1.Receive(System.Action)' and 'Class1.Receive<int>(System.Func<int>)'

好的,签名是一样的(虽然如果我不使用方法不会显示错误)。

如果我删除 Receive(Action) 方法,我会在 Receive(A) 中得到以下错误:

The type arguments for method 'Class1.Receive<T>(System.Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

但我的类型在这种情况下是无效的,并且禁止将其用作泛型参数。

那么,有没有办法让我的 Receive 方法不使用任何明确的 Action 或 Func 强制转换?

【问题讨论】:

    标签: c# generics signature void


    【解决方案1】:

    不,您不能这样做 - void 不是 Func&lt;T&gt; 的有效返回类型。你能做的最好的就是把它包装在Func&lt;object&gt;

    Receive(() => { A(); return null; });
    

    【讨论】:

    • 我得到与此代码相同的编译错误。但是return 0;return true; 有效!谢谢!
    【解决方案2】:

    尝试明确指定泛型类型参数:

    Receive<int>(B);
    

    【讨论】:

    • 有了这个,如果我有一个方法,例如,四个参数,我仍然需要做一个转换并包含所有这些参数。例如:Receive,string,int,int>(C,myObject1,string1,int1,int2)
    • 在这种情况下它并不是真正的强制转换(一切都发生在编译时),但我明白你的意思。你确定你需要这样一套通用的方法吗?
    • 是的,它是一个通用类,必须能够接受任何类型的方法。
    猜你喜欢
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多