Optional arguments in a generic Func<>

前端 未结 2 798
悲&欢浪女
悲&欢浪女 2020-12-20 13:38

I have the following method in an assembly:

public string dostuff(string foo, object bar = null) { /* ... */ }

I use it as a callback, so a

相关标签:
2条回答
  • 2020-12-20 13:58

    You can't do this, simply because optional arguments are syntactic sugars and can be only used if you are calling the method directly. When you call the method like this:

    dostuff(foo);
    

    Compiler translates it into:

    dostuff(foo, null);
    

    In other cases such as using a delegate that doesn't accept an optional argument or when calling this method using reflection, you have to provide the optional argument.

    0 讨论(0)
  • 2020-12-20 14:05

    You'll need to create a new method that accepts only one argument, and that passes the default value for the second argument. You could do this with a lambda, rather than creating a new named method, if you wanted:

    Func<string, string> doStuffDelegate = s => dostuff(s);
    

    The other option would be to use a delegate who's signature has an optional second argument, instead of using Func, in which case your method's signature would match:

    public delegate string Foo(string foo, object bar = null);
    

    You could assign dostuff to a delegate of type Foo directly, and you would be able to specify only a single parameter when invoking that delegate.

    0 讨论(0)
提交回复
热议问题