为什么 C# 不允许像 C++ 这样的非成员函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1024171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:47:15  来源:igfitidea点击:

Why C# is not allowing non-member functions like C++

c#.netfunctionc++-cliclr

提问by Navaneeth K N

C# will not allow to write non-member functions and every method should be part of a class. I was thinking this as a restriction in all CLI languages. But I was wrong and I found that C++/CLI supports non-member functions. When it is compiled, compiler will make the method as member of some unnamed class.

C# 不允许编写非成员函数,每个方法都应该是类的一部分。我认为这是所有 CLI 语言中的限制。但是我错了,我发现 C++/CLI 支持非成员函数。编译时,编译器会将方法作为某个未命名类的成员。

Here is what C++/CLI standard says,

这是 C++/CLI 标准所说的,

[Note: Non-member functions are treated by the CLI as members of some unnamed class; however, in C++/CLI source code, such functions cannot be qualified explicitly with that class name. end note]

The encoding of non-member functions in metadata is unspecified. [Note: This does not cause interop problems because such functions cannot have public visibility. end note]

[注意:CLI 将非成员函数视为某个未命名类的成员;但是,在 C++/CLI 源代码中,不能使用该类名显式限定此类函数。尾注]

元数据中非成员函数的编码未指定。[注意:这不会导致互操作问题,因为此类功能无法公开。尾注]

So my question is why don't C# implement something like this? Or do you think there should not be non-member functions and every method should belong to some class?

所以我的问题是为什么 C# 不实现这样的东西?或者你认为不应该有非成员函数,每个方法都应该属于某个类?

My opinion is to have non-member function support and it helps to avoid polluting class's interface.

我的观点是有非成员函数支持,它有助于避免污染类的接口。

Any thoughts..?

有什么想法吗..?

采纳答案by Eric Lippert

See this blog posting:

看到这个博客帖子:

http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-t-c-implement-top-level-methods.aspx

http://blogs.msdn.com/ericlippert/archive/2009/06/22/why-doesn-tc-implement-top-level-methods.aspx

(...)

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 stricting 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# 不实现功能 X?” 每时每刻。答案总是一样的:因为没有人设计、指定、实施、测试、记录和发布该功能。所有这六件事都是使功能发生所必需的。所有这些都花费了大量的时间、精力和金钱。功能并不便宜,而且我们非常努力地确保我们只发布那些在时间、精力和金钱预算有限的情况下为我们的用户带来最大好处的功能。

我知道这样一个笼统的答案可能没有解决具体问题。

在这种特殊情况下,过去明显的用户利益不足以证明随之而来的语言的复杂性是合理的。通过限制不同语言实体如何相互嵌套,我们 (1) 将合法程序限制为通用、易于理解的风格,以及 (2) 可以定义可理解、可指定、可实现、可测试的“标识符查找”规则和可记录的。

通过限制方法体总是在结构体或类中,我们可以更容易地推断调用上下文中使用的非限定标识符的含义;这样的东西始终是当前类型(或基类型)的可调用成员。

(……)

and this follow-up posting:

和这个后续帖子:

http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx

http://blogs.msdn.com/ericlippert/archive/2009/06/24/it-already-is-a-scripting-language.aspx

(...)

Like all design decisions, when we're faced with a number of competing, compelling, valuable and noncompossible ideas, we've got to find a workable compromise. We don't do that except by considering all the possibilites, which is what we're doing in this case.

(……)

像所有的设计决策一样,当我们面临许多相互竞争的、引人注目的、有价值的和不可组合的想法时,我们必须找到一个可行的折衷方案。我们不这样做,除非考虑所有的可能性,这就是我们在这种情况下所做的。

(emphasis from original text)

(重点来自原文)

回答by Jon Skeet

What's the benefit of notputting each method in a named class? Why would a non-member function "pollute" the class's interface? If you don't want it as part of the public API of a class, either don't make it public or don't put it in that class. You can always create a different class.

将每个方法放在命名类中有什么好处?为什么非成员函数会“污染”类的接口?如果您不想将其作为类的公共 API 的一部分,请不要将其公开或不要将其放在该类中。您始终可以创建不同的类。

I can't remember ever wanting to write a method floating around with no appropriate scope - other than anonymous functions, of course (which aren't really the same).

我不记得曾经想要编写一个没有适当范围的方法——当然,除了匿名函数(它们实际上并不相同)。

In short, I can't see any benefit in non-member functions, but I can see benefits in terms of consistency, naming and documentation in putting all methods in an appropriately named class.

简而言之,我看不到非成员函数有任何好处,但我可以看到将所有方法放在一个适当命名的类中的一致性、命名和文档方面的好处。

回答by Daniel Earwicker

The CLS (common language specification) says that you shouldn't have non-member functions in a library that conforms to the CLS. It's like an extra set of restrictions in addition to the basic restrictions of the CLI (common language interface).

CLS(通用语言规范)说在符合 CLS 的库中不应该有非成员函数。它就像是在 CLI(通用语言接口)的基本限制之外的额外限制。

It is possible that a future version of C# will add the ability to write a usingdirective that allows the static members of a class to be accessed without the class name qualification:

C# 的未来版本可能会添加编写using指令的功能,该指令允许在没有类名限定的情况下访问类的静态成员:

using System.Linq.Enumerable; // Enumerable is a static class

...

IEnumerable<int> range = Range(1, 10); // finds Enumerable.Range

Then there will be no need to change the CLS and existing libraries.

这样就无需更改 CLS 和现有库。

These blog posts demonstrate a libraryfor functional programming in C#, and they use a class name that is just one letter long, to try and cut down the noise caused by the requirement to qualify static method calls. Examples like that would be made a little nicer if usingdirectives could target classes.

这些博客文章演示了一个用于 C# 函数式编程的库,它们使用一个只有一个字母长的类名,以尝试减少由限定静态方法调用的要求引起的噪音。如果using指令可以针对类,这样的例子会更好一些。

回答by Cade Roux

I think you really need to clarify what you would want to create non-member static methods to achieve.

我认为你真的需要澄清你想要创建非成员静态方法来实现什么。

For instance, some of the things you might want them for could be handled with Extension Methods

例如,您可能需要它们的某些事情可以使用扩展方法处理

Another typical use (of a class which only contains static methods) is in a library. In this case, there is little harm in creating a class in an assembly which is entirely composed of static methods. It keeps them together, avoids naming collisions. After all, there are static methods in Math which serve the same purpose.

另一个典型用途(仅包含静态方法的类)是在库中。在这种情况下,在完全由静态方法组成的程序集中创建类几乎没有什么害处。它将它们保持在一起,避免命名冲突。毕竟,Math 中有一些静态方法可以达到同样的目的。

Also, you should not necessarily compare C++'s object model with C#. C++ is largely (but not perfectly) compatible with C, which didn't have a class system at all - so C++ had to support this programming idiom out of the C legacy, not for any particular design imperative.

此外,您不必将 C++ 的对象模型与 C# 进行比较。C++ 在很大程度上(但不是完美地)与 C 兼容,C 根本没有类系统——所以 C++ 必须支持 C 遗留之外的这种编程习惯,而不是为了任何特定的设计要求。

回答by Dmitry Tashkinov

Since Java, most programmers have easily accepted that any method is a member of a class. I doesn't make any considerable obstacles and make the concept of method more narrow, which make a language easier.

从 Java 开始,大多数程序员很容易接受任何方法都是类的成员。我没有设置任何相当大的障碍并使方法的概念更加狭窄,这使语言更容易。

However, indeed, class infers object, and object infers state, so the concept of class containing only static methods looks a little absurd.

但是,确实,类推断对象,对象推断状态,因此仅包含静态方法的类的概念看起来有点荒谬。

回答by Nemanja Trifunovic

Non member functions are a good thing because they improve encapsulationand reduce coupling between types. Most modern programming languages such as Haskell and F# support free functions.

非成员函数是一件好事,因为它们改进了封装并减少了类型之间的耦合。大多数现代编程语言(例如 Haskell 和 F#)都支持免费函数。

回答by jalf

C# doesn't allow it because Java didn't allow it.

C# 不允许,因为 Java 不允许。

I can think of several reasons why the designers of Java probably didn't allow it

我可以想到 Java 的设计者可能不允许它的几个原因

  • Java was designed to be simple. They attempted to make a language without random shortcuts, so that you generally have just one simple way to do everything, even if other approaches would have been cleaner or more concise. They wanted to minimize the learning curve, and learning "a class may contain methods" is simpler than "a class may contain methods, and functions may exist outside classes".
  • Superficially, it looks less object-oriented. (Anything that isn't part of an object obviously can't be object-oriented? Can it? of course, C++ says yes, but C++ wasn't involved in this decision)
  • Java 被设计成简单的。他们试图创造一种没有随机快捷方式的语言,因此您通常只有一种简单的方法来完成所有事情,即使其他方法会更清晰或更简洁。他们想要最小化学习曲线,学习“一个类可能包含方法”比“一个类可能包含方法,并且函数可能存在于类之外”更简单。
  • 从表面上看,它看起来不太面向对象。(任何不属于对象的东西显然不能是面向对象的?可以吗?当然,C++ 说是的,但 C++ 没有参与这个决定)

As I already said in comments, I think this is a good question, and there are plenty of cases where non-member functions would've been preferable. (this part is mostly a response to all the other answers saying "you don't need it")

正如我在评论中已经说过的,我认为这是一个很好的问题,在很多情况下,非成员函数会更可取。(这部分主要是对所有其他回答说“你不需要它”的回应)

In C++, where non-member functions are allowed, they are often preferred, for several reasons:

在 C++ 中,允许使用非成员函数,它们通常是首选,原因如下:

  • It aids encapsulation. The fewer methods have access to the private members of a class, the easier that class will be to refactor or maintain. Encapsulation is an important part of OOP.
  • Code can be reused much easier when it is not part of a class. For example, the C++ standard library defines std::findor std::sort` as non-member functions, so that they can be reused on any type of sequences, whether it is arrays, sets, linked lists or (for std::find, at least) streams. Code reuse is also an important part of OOP.
  • It gives us better decoupling. The findfunction doesn't need to know about the LinkedList class in order to be able to work on it. If it had been defined as a member function, it would be a member of the LinkedList class, basically merging the two concepts into one big blob.
  • Extensibility. If you accept that the interface of a class is not just "all its public members", but also "all non-member functions that operate on the class", then it becomes possible to extend the interface of a class without having to edit or even recompile the class itself.
  • 它有助于封装。可以访问类的私有成员的方法越少,该类就越容易重构或维护。封装是OOP的重要组成部分。
  • 当代码不是类的一部分时,它可以更容易地重用。例如,C++ 标准库将std::findstd::sort` 定义为非成员函数,以便它们可以在任何类型的序列上重用,无论是数组、集合、链表或(对于 std::find,at最少)流。代码重用也是 OOP 的重要组成部分。
  • 它为我们提供了更好的解耦。该find函数不需要知道 LinkedList 类就可以处理它。如果它被定义为一个成员函数,它就会是 LinkedList 类的一个成员,基本上将两个概念合并为一个大 blob。
  • 可扩展性。如果您接受类的接口不仅是“其所有公共成员”,而且是“对类进行操作的所有非成员函数”,那么就可以扩展类的接口而无需编辑或甚至重新编译类本身。

The ability to have non-member functions may have originated with C (where you had no other choice), but in modern C++, it is a vital feature in its own right, not just for backward-comparibility purposes, but because of the simpler, cleaner and more reusable code it allows.

拥有非成员函数的能力可能起源于 C(在那里你别无选择),但在现代 C++ 中,它本身就是一个重要的特性,不仅仅是为了向后比较的目的,而且因为更简单,它允许更干净和更可重用的代码。

In fact, C# seems to have realized much the same things, much later. Why do you think extension methods were added? They are an attempt at achieving the above, while preserving the simple Java-like syntax. Lambdas are also interesting examples, as they too are essentially small functions defined freely, not as members of any particular class. So yes, the concept of non-member functions is useful, and C#'s designers have realized the same thing. They've just tried to sneak the concept in through the back door.

事实上,C# 似乎已经实现了很多相同的事情,但要晚得多。为什么你认为添加了扩展方法?它们是实现上述目标的一种尝试,同时保留了类似 Java 的简单语法。Lambda 也是有趣的例子,因为它们本质上也是自由定义的小函数,而不是任何特定类的成员。所以是的,非成员函数的概念很有用,C# 的设计者也意识到了同样的事情。他们只是试图从后门偷偷摸摸这个概念。

http://www.ddj.com/cpp/184401197and http://www.gotw.ca/publications/mill02.htmare two articles written by C++ experts on the subject.

http://www.ddj.com/cpp/184401197http://www.gotw.ca/publications/mill02.htm是 C++ 专家就该主题撰写的两篇文章。

回答by Jason Baker

Bear something in mind: C++ is a much more complicated language than C#. And although they may be similiar syntactically, they are very different beasts semantically. You wouldn't think it would be terribly difficult to make a change like this, but I could see how it could be. ANTLR has a good wiki page called What makes a language problem hard?that's good to consult for questions like this. In this case:

请记住:C++ 是一种比 C# 复杂得多的语言。尽管它们在句法上可能相似,但它们在语义上却是截然不同的野兽。你不会认为做出这样的改变会非常困难,但我可以看到它是如何发生的。ANTLR 有一个很好的 wiki 页面,称为什么使语言问题变得困难?像这样的问题咨询是很好的。在这种情况下:

Context sensitive lexer? You can't decide what vocabulay symbol to match unless you know what kind of sentence you are parsing.

上下文敏感词法分析器?除非您知道要解析的句子类型,否则您无法确定要匹配的词汇符号。

Now instead of just worrying about functions defined in classes, we have to worry about functions defined outside classes. Conceptually, there isn't much difference. But in terms of lexing and parsing the code, now you have the added problem of having to say "if a function is outside a class, it belongs to this unnamed class. However, if it is inside the class, then it belongs to that class."

现在,我们不仅要担心在类中定义的函数,还要担心在类外定义的函数。从概念上讲,没有太大区别。但是在词法分析和代码解析方面,现在你不得不说“如果一个函数在一个类之外,它属于这个未命名的类。但是,如果它在类内部,那么它属于那个类”班级。”

Also, if the compiler comes across a method like this:

另外,如果编译器遇到这样的方法:

public void Foo()
{
    Bar();
}

...it now has to answer the question "is Bar located within this class or is it a global class?"

...它现在必须回答“Bar 是位于这个类中还是它是一个全局类?”的问题。

Forward or external references? I.e., multiple passes needed? Pascal has a "forward" reference to handle intra-file procedure references, but references to procedures in other files via the USES clauses etc... require special handling.

转发或外部引用?即,需要多次通过?Pascal 有一个“转发”引用来处理文件内过程引用,但是通过 USES 子句等引用其他文件中的过程需要特殊处理。

This is another thing that causes problems. Remember that C# doesn't require forward declarations. The compiler will make one pass just to determine what classes are named and what functions those classes contain. Now you have to worry about finding classes andfunctions where functions can be either inside or outside of a class. This is something a C++ parser doesn't have to worry about as it parses everything in order.

这是导致问题的另一件事。请记住,C# 不需要前向声明。编译器将通过一次来确定命名了哪些类以及这些类包含哪些函数。现在您必须担心查找函数可以位于类内部或外部的类函数。这是 C++ 解析器不必担心的事情,因为它会按顺序解析所有内容。

Now don't get me wrong, it could probably be done in C#, and I would probably use such a feature. But is it really worth all the trouble of overcoming these obstacles when you could just type a class name in front of a static method?

现在不要误会我的意思,它可能可以在 C# 中完成,我可能会使用这样的功能。但是,当您只需在静态方法前输入类名时,克服这些障碍是否真的值得?

回答by Yuliy

  • Having all code lie within classes allows for a more powerful set of reflection capabilities.
  • It allows the use of static intializers, which can initialize the data needed by static methods within a class.
  • It avoids name clashes between methods by explicitly enclosing them within a unit that cannot be added to by another compilation unit.
  • 将所有代码放在类中可以提供更强大的反射功能。
  • 它允许使用静态初始化器,它可以初始化类中静态方法所需的数据。
  • 它通过将方法显式地包含在另一个编译单元无法添加的单元中来避免方法之间的名称冲突。

回答by Patrick Fromberg

Free functions are very useful if you combine them with duck typing. The whole C++ STL is based on it. Hence I am sure that C# will introduce free functions when they manage to add true generics.

如果将自由函数与鸭子类型结合使用,它们将非常有用。整个 C++ STL 都基于它。因此,我确信 C# 在设法添加真正的泛型时会引入自由函数。

Like economics, language design is also about psychology. If you create appetite for true generics via free functions in C# and not deliver, then you would kill C#. Then all C# developers would move to C++ and nobody wants that to happen, not the C# community and most certainly not those invested in C++.

与经济学一样,语言设计也与心理学有关。如果您通过 C# 中的免费函数对真正的泛型产生兴趣而不交付,那么您将扼杀 C#。然后所有 C# 开发人员都将转向 C++,没有人希望这种情况发生,C# 社区和投资 C++ 的人当然也不会。