我有一个接受两个delegate
s作为参数的方法。
method1(Delegate delegate1,Delegate delegate2,params Object[] parameters)
{
// There is lot of other code, I haven't put here. To make it clear.
string key = delegate1.DynamicInvoke(parameters);
object instance = delegate2.DynamicInvoke(parameters);
// Getting errors here, as parameters mismatch.
}
// Code from the Calling class
// There are many other classes in my project, which are calling Method1,
// but the number of parameters of method2 and method3 always vary.
private string Method2(object[] paramsObject)
{
string key = string.Empty;
foreach (object obj in paramsObject)
{
key += obj.ToString() + "|";
}
return key.Trim(new char[]{'|'});
}
private object Method3(object[] paramsObject)
{
object object1 = paramsObject[0];
object object2 = paramsObject[1];
object object3 = paramsObject[2];
object object4 = GetObjectUsingParameters(object1,object2,object3);
return object4;
}
Func<string, string, string> Method2Delegate = Method2;
Func<object1,object2,object3,object4> Method3Delegate = Method3;
//Calling Method1
Method1(Method2Delegate,Method3Delegate,string str1,string str2,object object1,Object object2,Object object3);
我在Method1
调用delegate
s参数不匹配错误时收到错误。
因为我们最后只能有一个params参数作为方法的输入。
您能否告诉我,如何将参数绑定到同一delegate
或如何解决此问题?
非常感谢。
答案 0 :(得分:0)
您需要使用下一个签名创建委托:
delegate void MyCustomDelegate (params object[] params);
然后将Method2Delegate和Method3Delegate定义为MyCustomDelegate类型。
答案 1 :(得分:0)
这样做是怎么回事:
method1(Func<object[],string> delegate1,Func<object[], object> delegate2,params Object[] parameters)
{
// There is lot of other code, I haven't put here. To make it clear.
string key = delegate1(parameters);
object instance = delegate2(parameters);
// Getting errors here, as parameters mismatch.
}
并且在来电者处
Method1(Method2,Method3,string str1,string str2,object object1,Object object2,Object object3);
这样您就不需要定义动态调用的委托。