如何传递一个可选参数作为参数的方法? [英] How to pass a method with optional parameters as an argument?

查看:115
本文介绍了如何传递一个可选参数作为参数的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我们有 ClassA ,方法 Foo 包含一个可选参数。所以,我们可以使用它,如方法 DoFoo 中所示。

Say, we have ClassA with method Foo containing an optional parameter. So, we can use it as shown in method DoFoo.

public class ClassA
{
    public ClassA() { }

    public void Foo(bool flag = true)
    {
    }

    public void DoFoo()
    {
        Foo(); // == Foo(true);
    }
}

一旦我需要传递给另一个类code> ClassB 。首先,我试图将它作为 Action 传递,但签名肯定不匹配。然后我将其作为 Action< string> 传递,签名匹配,但 ClassB 中的参数不再是可选的。但是我确实想要它是可选的,并提出宣布一个代表的想法。所以,它的工作。

Once I needed to pass it to another class ClassB. First I tried to pass it as Action, but the signature surely didn't match. Then I passed it as Action<string>, the signature matched, but the parameter in ClassB was no longer optional. But I did wanted to have it optional and came to an idea to declare a delegate. So, it worked.

public delegate void FooMethod(bool flag = true);

public class ClassB
{
    Action<bool> Foo1;
    FooMethod Foo2;

    public ClassB(Action<bool> _Foo1, FooMethod _Foo2)
    {
        Foo1 = _Foo1;
        Foo2 = _Foo2;
    }

    public void DoFoo()
    {
        Foo1(true);
        Foo2(); // == Foo2(true);
    }

所以,问题是:我可以以某种方式传递一个可选参数的方法作为一个参数,没有明确声明一个委托并保持其参数的可选质量?

So, the question is: can I somehow pass a method with an optional parameter as an argument without explicitly declaring a delegate and keep the optional quality of its parameters?

推荐答案


,问题是:我可以以某种方式传递一个可选参数作为参数的方法,而不显式声明一个委托,并保留其参数的可选质量?

So, the question is: can I somehow pass a method with an optional parameter as an argument without explicitly declaring a delegate and keep the optional quality of its parameters?

不。 可选性是方法的签名的一部分,编译器在编译时需要知道这个方法,以提供默认值。如果您使用不具有可选参数的委托类型,那么当您尝试在没有足够参数的情况下调用它时,编译器的意图是什么?

No. The "optionality" is part of the signature of the method, which the compiler needs to know at at compile time to provide the default value. If you're using a delegate type that doesn't have the optional parameter, what is the compiler meant to do when you try to call it without enough arguments?

最简单的方法可能是包装它:

The simplest approach is probably to wrap it:

CallMethod(() => Foo()); // Compiler will use default within the lambda.
...
public void Foo(bool x = true) { ... }

public void CallMethod(Action action) { ... }

这篇关于如何传递一个可选参数作为参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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