-1

我正在寻找使用函数委托调用带参数的方法的方法。

您可以在该位置使用函数委托,而不是调用 processOperationB。但寻找可以实现以下方式的任何方式。

public class Client
{

    public AOutput OperationA (string param1, string param2)
    {
    //Some Operation 
    }

    public BOutput  OperationB(string param1, string param2)
    {
        //Some Operation 
    }
}


public class Manager 
{
    private Client cl;



    public Manager()
    {
        cl=new Client();
    }


    private void processOperationA(string param1, string param2)
    {

        var res = cl.OperationA(param1,param2); 
        //...   

    }

    private void processOperationB(string param1, string param2)
    {
        var res = cl.OperationB(param1,param2); 

        // trying to Call using the GetData , in that case I could get rid of individual menthods for processOperationA, processOperationB

        var res= GetData<BOutput>( x=> x.OperationB(param1,param2));
    }


    // It could have been done using Action, but it should return a value 
    private T GetData<T>(Func<Client,T> delegateMethod)
    {

    // how a Function delegate with params can be invoked 
    // Compiler expects the arguments to be passed here. But have already passed all params .

        delegateMethod();


    }

}
4

1 回答 1

2

您的评论内容如下:

编译器期望在此处传递参数

但事实并非如此。是的,它需要一个参数,但不是你认为它所期望的。

您的delegateMethod参数是 a Func<Client, T>,这意味着它需要一个 type 的参数Client,并返回一个 type 的值T。根据您显示的代码,您应该改为编写以下代码:

private T GetData<T>(Func<Client,T> delegateMethod)
{
    return delegateMethod(cl);
}

我不清楚您要解决的更广泛的问题是什么。我没有看到该GetData<T>()方法在此处添加任何内容;我认为,调用者可以在每种情况下调用适当的“操作...”方法(即在您的processOperationA()方法中)。

但至少我们可以解决编译器错误。如果您想在更广泛的问题上寻求帮助,您可以发布一个新问题。确保包含一个良好的最小化、可验证和完整的代码示例,清楚地显示您正在尝试做什么,并准确解释您尝试过的内容和无效的内容。

于 2016-11-05T02:21:33.690 回答