gpt4 book ai didi

c# - 扩展方法是 C# 的面向对象特性吗?

转载 作者:太空狗 更新时间:2023-10-30 00:12:55 24 4
gpt4 key购买 nike

扩展方法是否遵循 C# 中面向对象的范例?

使用扩展方法是一种好习惯吗?

在软件开发生命周期中,我们应该如何在设计阶段考虑这个问题?

最佳答案

Eric Lippert 有 blogged about this我怀疑除了引用他的话我不能做得更好:

So, yes, the oft-heard criticism that "extension methods are not object-oriented" is entirely correct, but also rather irrelevant. Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress.

They're also incredibly convenient and make LINQ possible, which is why we added them. The fact that they do not conform to some philosophical ideal of what makes an object-oriented language was not really much of a factor in that decision.

不过,我要补充一点,它们的用处不仅仅局限于 LINQ - 原因与它们 LINQ 中的用处相同。能够表达适用于特定接口(interface)的任意实现的算法真的很棒(例如 LINQ to Obhects 中的 IEnumerable<T>)。此类算法通常没有您正在处理的接口(interface)之外的任何上下文,因此它们通常自然是静态的。

如果您承认您拥有一些静态实用方法,您更愿意使用哪种语法?

// Traditional
CollectionUtils.Sort(collection);

// Extension methods
collection.Sort();

在我看来,后者只是更具可读性。它简洁地表达了你想做什么。它并没有明确如何你想做什么,但是对于大多数来说这并不重要 - 而当你调试那条特定的行时更重要,当然。

关于c# - 扩展方法是 C# 的面向对象特性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1802380/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com