Extension methods versus inheritance

前端 未结 9 1952
盖世英雄少女心
盖世英雄少女心 2020-12-13 00:25

Are there rules of thumb that help determine which to use in what case? Should I prefer one over the other most times?

Thanks!

9条回答
  •  盖世英雄少女心
    2020-12-13 00:26

    MSDN

    In the page on extension methods in the C# programming guide it says:

    General Guidelines

    In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type. For more information, see Inheritance (C# Programming Guide).

    When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break.

提交回复
热议问题