c# - 如何传递带有可选参数作为参数的方法?

标签 c# delegates optional-parameters

比如说,我们有ClassA使用方法Foo包含可选参数。所以,我们可以按照方法 DoFoo 所示使用它。 .

public class ClassA
{
    public ClassA() { }

    public void Foo(bool flag = true)
    {
    }

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

有一次我需要将它传递给另一个类 ClassB 。首先我尝试将其传递为 Action ,但签名肯定不匹配。然后我将其传递为 Action<string> ,签名匹配,但是ClassB中的参数不再是可选的。但我确实想让它成为可选的,并想到了声明一个委托(delegate)的想法。所以,它起作用了。

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);
    }

所以,问题是:我能否以某种方式传递一个带有可选参数作为参数的方法,而无需显式声明委托(delegate)并保持其参数的可选质量?

最佳答案

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?

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

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

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

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

关于c# - 如何传递带有可选参数作为参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728844/

相关文章:

c# - 如何使数据表中的单元格为空白而不是 0?

c# - 聚焦时如何自动打开组合框?

c# - 为什么在 Class<T> 中声明 Delegate<T> 会生成 VS 警告?

c# - 方法参数数组默认值

c++ - 带有可选参数的 boost 函数

c# - Linq 何时自动调用实现 IEnumerator<T> 的类的 Dispose()?

c# - 获取 "Tuple element name is inferred. Please use language version 7.1 or greater to access an element by its inferred name."

c# - 为什么在 C# 中不允许将此命名函数作为 Func<> 参数传递?

swift - 如何修复 "does not conform to protocol"

java - 在 Java 中模拟可选参数的更好方法是什么?