通用Func中的可选参数. [英] Optional arguments in a generic Func<>
问题描述
我在程序集中具有以下方法:
I have the following method in an assembly:
public string dostuff(string foo, object bar = null) { /* ... */ }
我将其用作回调,因此对它的引用将传递给另一个程序集,例如:
I use it as a callback, so a reference to it is passed to another assembly as such:
Func<string, object, string> dostuff
现在以原始形式,无需指定第二个参数(默认为null
)就可以调用它.但是,当我将它用作第二个程序集中的回调时,必须指定第二个参数.
Now in the original form, I can call it without specifying that second argument, which defaults to null
. But when I use it as a callback in that second assembly, I must specify that second argument.
什么语法允许我忽略第二个参数?
推荐答案
您将需要创建一个新方法,该方法仅接受一个参数,并传递第二个参数的默认值.如果需要,您可以使用lambda来执行此操作,而不是创建一个新的命名方法:
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);
另一种选择是使用签名具有可选的第二个参数的委托,而不是使用Func
,在这种情况下,方法的签名将匹配:
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);
您可以直接将dostuff
分配给Foo
类型的委托,并且在调用该委托时只能指定一个参数.
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.
这篇关于通用Func中的可选参数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!