现在 c# 中的方法签名是什么?

What is a method signature in c# now?

Stack Overflow 上有几个关于 C# 中的方法签名的问题。几乎所有的解决方案都说 return 值和访问级别不是方法签名的一部分。但是我在 MSDN completely opposite information.

上找到了

Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.

A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

我很困惑。真相是什么?

根据 C# 语言规范的第 3.6 节,方法签名不包括 return 类型(显式)或访问修饰符(省略):

The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.

他们只是没有在非常严格的意义上使用术语 'signature'。第一次使用严格,第二次使用不严格。 他们想强调的是,对于代表来说,签名和return类型都很重要。

请注意,MSDN 是一个指南,而不是规范。有时他们会做一些简化或更宽松的术语。

C# 规范将签名定义为不包含 return 类型。 CLI 规范将其定义为包含 return 类型。

尽管这个小差异令人遗憾,但不难从上下文中推断出其含义。正如您引用的文本所示, return 类型在将方法与委托匹配时是相关的;在进行虚拟覆盖时以及许多其他情况下,它也很重要。 return 类型在重载解析期间不相关,这是 C# 规范最关心方法的 "signature" 的上下文。