带有可选参数的委托引发运行时异常 [英] Delegate with optional parameter throws runtime exception

查看:79
本文介绍了带有可选参数的委托引发运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

I have code like this:

private delegate string MyDelegate(int requiredParameter, int optionalParameter = -1);
private string MyMethod(int requiredParameter, int optionalParameter = -1)
{
    return "Some return value";
}



然后我这样称呼:



Which I then call like this:

string s = (string)this.Invoke(new MyDelegate(MyMethod), new object[] { 10 });



基于一些 我在StackOverflow上看到,我认为我想做的事情是可能的,但是最后一行抛出TargetParameterCountException和消息Parameter count mismatch.

知道为什么会这样吗?我可以使其以某种比重载更优雅的方式工作吗?



Based on some questions I saw on StackOverflow, I think that what I''m trying to do is possible, but this last line throws a TargetParameterCountException with the message Parameter count mismatch.

Any idea why this happens? Can I make it work in some manner that is more elegant than overloading?

推荐答案

请参考一次:
http://stackoverflow.com/questions/2484226/invoking-eventhandler-generic-targetparametercountexception [ ^ ]
please refer once:
http://stackoverflow.com/questions/2484226/invoking-eventhandler-generic-targetparametercountexception[^]


如果您知道要调用的方法,则
If you know which method you are calling then
string s = (string)this.Invoke(new MyDelegate(MyMethod), new object[] { 10 });


只是没有意义的


is pointless just do

string s = MyMethod(10);


但是,如果您的方法是动态的,则将其设置为


However if your method is dynamic then it would be set somewhere like

private MyDelegate _mydelegate;

public void SetDelegate(MyDelegate del)
{
   _mydelegate = del;
}


你会用
称呼它


and you would call this by

private void somemethod()
{
     string s = _del(10); //using the defined delegate
}


这篇关于带有可选参数的委托引发运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆