Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

c# - 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

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.

What syntax allows me to ignore that second argument?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...