What is the motivation behind “Use Extension Methods Sparingly?”

前端 未结 7 1845
慢半拍i
慢半拍i 2021-02-05 23:38

I find them a very natural way to extend existing classes, especially when you just need to \"spot-weld\" some functionality onto an existing class.

Microsoft says, \"In

7条回答
  •  借酒劲吻你
    2021-02-05 23:44

    Extension methods can be thought of as Aspect Oriented. I believe Microsoft is saying, if you have the source code, you should be altering the original class. It has to do with clarity and ease of maintenance. The reason extension methods were needed is that they extend functionality of existing objects. In the case of LINQ, if you dig into how it works, objects can be created with a variety of types that cannot be known ahead of time. Using extension methods allows some behaviors to be added.

    For example, it makes sense to extend .NET framework objects because you don't have the source, but may have some behavior to add to an object. Extending the string, DateTime and FrameworkElement classes is acceptable. It may also be acceptable to create extension methods for classes that cross application boundaries. Say, if you wanted to share a DTO class and have some specific UI behaviour, create that extension method in the UI only.

    With dynamic languages, the paradigm is different, but I believe you're talking about C# and VB.net.

提交回复
热议问题