C# 参数为c的函数委托#
我正在寻找使用函数委托调用带有参数的方法 您可以在此处使用函数委托,而不是调用processOperationB。但是寻找任何可以实现以下方法的方法C# 参数为c的函数委托#,c#,generics,anonymous-delegates,C#,Generics,Anonymous Delegates,我正在寻找使用函数委托调用带有参数的方法 您可以在此处使用函数委托,而不是调用processOperationB。但是寻找任何可以实现以下方法的方法 public class Client { public AOutput OperationA (string param1, string param2) { //Some Operation } public BOutput OperationB(string param1, string par
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();
}
}
公共类客户端
{
公共AOOUTPUT操作A(字符串参数1,字符串参数2)
{
//一些手术
}
公共BOutput操作B(字符串参数1,字符串参数2)
{
//一些手术
}
}
公共班级经理
{
私人客户cl;
公共经理()
{
cl=新客户端();
}
私有void processOperationA(字符串param1,字符串param2)
{
var res=cl.OperationA(参数1,参数2);
//...
}
私有void processOperationB(字符串param1,字符串param2)
{
var res=cl.OperationB(参数1,参数2);
//尝试使用GetData调用,在这种情况下,我可以摆脱processOperationA、processOperationB的单独方法
var res=GetData(x=>x.OperationB(param1,param2));
}
//可以使用Action完成,但它应该返回一个值
私有T GetData(Func delegateMethod)
{
//如何调用带有参数的函数委托
//编译器希望在此处传递参数。但已传递所有参数。
delegateMethod();
}
}
您的评论如下:
编译器希望在此处传递参数
但事实并非如此。是的,它需要争论,但不是你认为它需要的
您的delegateMethod
参数是Func
,这意味着它需要一个Client
类型的参数,并返回一个T
类型的值。根据显示的代码,您应该编写以下代码:
private T GetData<T>(Func<Client,T> delegateMethod)
{
return delegateMethod(cl);
}
private T GetData(Func delegateMethod)
{
返回委托方法(cl);
}
我不清楚你们要解决的更广泛的问题是什么。我没有看到GetData()
方法在这里添加任何内容;我认为,在每种情况下,调用者都可以调用适当的“Operation…”方法(即在processOperationA()
方法中)
但至少我们可以解决编译器错误。如果你想在更广泛的问题上得到帮助,你可以发布一个新问题。确保包含一个好的代码,清楚地显示您正在尝试做什么,并准确地解释您尝试了什么和哪些不起作用。好的,那么代码有什么问题?你有错误吗?什么错误?不清楚你想做什么。。。为什么要调用
GetData
,因为您可以直接执行代码。。。