Extension methods versus inheritance

前端 未结 9 1951
盖世英雄少女心
盖世英雄少女心 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:35

    They are very different, for example LINQ standard query operators are great example of extension methods that should be difficult to implement with inheritance, but if you have access to class and can change source it will be better to use inheritance,
    EDIT
    and here is some rules that I find here C# 3.0 Features: Extension Methods

    • Extension methods cannot be used to override existing methods
    • An extension method with the same name and signature as an instance method will not be called
    • The concept of extension methods cannot be applied to fields, properties or events
    • Use extension methods sparingly....overuse can be a bad thing!

提交回复
热议问题