使用带有可选参数的方法的C#委托 [英] Using C# delegates with methods with optional parameters

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

问题描述

是否有机会使此代码工作?当然,我可以对Foo做出第二个定义,但是我认为这是一个很不优雅的东西;)

  delegate int Del(int x); 

static int Foo(int a,int b = 123)
{
return a + b;
}

static void Main()
{
Del d = Foo;
}


解决方案

您的代表要求正好一个参数,而您的 Foo()方法在最多两个参数中要求(编译器提供未指定的默认值调用参数)。因此,方法签名是不同的,所以你不能以这种方式关联它们。



为了使其工作,你需要重载你的 Foo ()方法(如你所说),或者用可选参数声明你的委托:

  int Del(int x,int y = 123); 

顺便提一下,请注意,如果您在委托中声明不同的默认值,并且执行方法,使用代理类型定义的默认值



就是这个代码打印 457 而不是 124 因为 d是Del



int {int x,int y = 456);

static int Foo(int a,int b = 123)
{
return a + b;
}

static void Main()
{
Del d = Foo;

Console.WriteLine(d(1));
}


Is there a chance to make this code work? Of course I can make second definition of Foo, but I think it'd be a little non-elegant ;)

delegate int Del(int x);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;
}

解决方案

Your delegate asks for exactly one parameter, while your Foo() method asks for at most two parameters (with the compiler providing default values for unspecified call arguments). Thus the method signatures are different, so you can't associate them this way.

To make it work, you need to either overload your Foo() method (like you said), or declare your delegate with the optional parameter:

delegate int Del(int x, int y = 123);

By the way, bear in mind that if you declare different default values in your delegate and the implementing method, the default value defined by the delegate type is used.

That is, this code prints 457 instead of 124 because d is Del:

delegate int Del(int x, int y = 456);

static int Foo(int a, int b = 123)
{ 
    return a+b; 
}

static void Main()
{
    Del d = Foo;

    Console.WriteLine(d(1));
}

这篇关于使用带有可选参数的方法的C#委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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