What's so great about Func<> delegate?

前端 未结 6 641
迷失自我
迷失自我 2020-12-12 13:57

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

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 14:30

    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.

提交回复
热议问题