gpt4 book ai didi

c# - 作为静态类的一部分与[理论上]作为 namespace 的一部分,扩展方法是否以任何实际方式受益?

转载 作者:太空狗 更新时间:2023-10-29 21:40:49 25 4
gpt4 key购买 nike

当谈到扩展方法时,类名似乎什么都不做,但提供了一个分组,这正是 namespace 所做的。一旦包含命名空间,我就会在命名空间中获得所有扩展方法。所以我的问题归结为:我可以从静态类中的扩展方法中获得一些值(value)吗?

我意识到将它们放入静态类是编译器的要求,但从组织的角度来看,允许在没有类的 namespace 中定义扩展方法是合法的似乎是合理的围绕着他们。以另一种方式重新表述上述问题:在某些情况下,作为开发人员,将扩展方法附加到类而不是附加到 namespace 是否有任何实际好处或帮助?

我基本上只是想获得一些直觉、确认或洞察力——我怀疑这可能是最容易实现扩展方法的方式,不值得花时间让扩展方法独立存在在 namespace 中。

最佳答案

或许您会在 Eric Lippert 的博文 Why Doesn't C# Implement "Top Level" Methods? 中找到满意的答案(反过来由 SO 问题 Why C# is not allowing non-member functions like C++ 提示),从何而来(我的重点):

I am asked "why doesn't C# implement feature X?" all the time. The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given our constrained time, effort and money budgets.

I understand that such a general answer probably does not address the specific question.

In this particular case, the clear user benefit was in the past not large enough to justify the complications to the language which would ensue. By restricting how different language entities nest inside each other we (1) restrict legal programs to be in a common, easily understood style, and (2) make it possible to define "identifier lookup" rules which are comprehensible, specifiable, implementable, testable and documentable.

By restricting method bodies to always be inside a struct or class, we make it easier to reason about the meaning of an unqualified identifier used in an invocation context; such a thing is always an invocable member of the current type (or a base type).

关于c# - 作为静态类的一部分与[理论上]作为 namespace 的一部分,扩展方法是否以任何实际方式受益?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10340860/

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