Why is Action/Func better than a regular Method in .Net?

前端 未结 5 430
滥情空心
滥情空心 2020-12-28 19:28

I much prefer using an Action or a Func if I need a quick reusable piece of code, however others on my team don\'t like them or understand them.
At the moment my only re

5条回答
  •  孤城傲影
    2020-12-28 19:42

    In general I agree with the other answerers: Blindly replacing function definitions with Action/Func is not a good thing. Action and Func are not the future of .NET. They are a tool which is very useful but like any tool can be misused.

    So if you tend to write code like this

    class SomeClass {
        Action<...> a1 = (..) => {};
        Func<...> f1 = (..) => {};
        Action<...> a2 = (..) => {};
        ...
    }
    

    That is certainly not a good thing.

    If you do this a lot:

      void SomeMethod()
      {
          Action<..> a = (..) => {};
          ...
          a();
      }
    

    then this is actually a good way of encapsulating a little helper method without polluting the class.

    To argue your specific case: If hideControl is only used in a very specific case the private helper method would be preferred. If it is required for a lot of FormViews then the extension method makes more sense. Extension methods are also a tool which can be misused as it can lead to pollution of the public interface for a class. Although you can limit it through the use of namespaces.

    I usually go by this guideline: If you require a helper method which is useful in a lot of places and situations and can be made fairly generic I create an extension method. If it is a helper method which is required for a specific class but in a several places (methods) in that class then I create a private method. If it is a helper which I only need in one specific place then I make it a Action/Func inside that method.

提交回复
热议问题