带参数的函数委托c#

本文关键字:函数 参数 | 更新日期: 2023-09-27 18:16:29

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

您可以在该位置使用函数委托而不是调用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();

    }
}

带参数的函数委托c#

您的评论如下:

编译器期望在这里传递参数

但事实并非如此。是的,它需要一个参数,但不是你想的那样。

您的delegateMethod参数是Func<Client, T>,这意味着它需要一个类型为Client的参数,并返回类型为T的值。根据您所展示的代码,您应该这样写:

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

我不清楚你想解决的更大的问题是什么。我没有看到GetData<T>()方法在这里添加任何东西;调用者可以调用适当的"Operation…"方法在每种情况下,我认为(即在你的processOperationA()方法)。

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