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
542 views
in Technique[技术] by (71.8m points)

lambda - What's so great about Func<> delegate?

Sorry if this is basic but I was trying to pick up on .Net 3.5.

Question: Is there anything great about Func<> and it's 5 overloads? From the looks of it, I can still create a similar delgate on my own say, MyFunc<> with the exact 5 overloads and even more.

eg: public delegate TResult MyFunc<TResult>() and a combo of various overloads...

The thought came up as I was trying to understand Func<> delegates and hit upon the following scenario:

Func<int,int> myDelegate = (y) => IsComposite(10);

This implies a delegate with one parameter of type int and a return type of type int. There are five variations (if you look at the overloads through intellisense). So I am guessing that we can have a delegate with no return type?

So am I justified in saying that Func<> is nothing great and just an example in the .Net framework that we can use and if needed, create custom "func<>" delegates to suit our own needs?

Thanks,

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The greatness lies in establishing shared language for better communication.

Instead of defining your own delegate types for the same thing (delegate explosion), use the ones provided by the framework. Anyone reading your code instantly grasps what you are trying to accomplish.. minimizes the time to 'what is this piece of code actually doing?' So as soon as I see a

  • Action = some method that just does something and returns no output
  • Comparison = some method that compares two objects of the same type and returns an int to indicate order
  • Converter = transforms Obj A into equivalent Obj B
  • EventHandler = response/handler to an event raised by some object given some input in the form of an event argument
  • Func = some method that takes some parameters, computes something and returns a result
  • Predicate = evaluate input object against some criteria and return pass/fail status as bool

I don't have to dig deeper than that unless it is my immediate area of concern. So if you feel the delegate you need fits one of these needs, use them before rolling your own.

Disclaimer: Personally I like this move by the language designers.

Counter-argument : Sometimes defining your delegate may help communicate intent better. e.g. System.Threading.ThreadStart over System.Action. So it’s a judgment call in the end.


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

...