关于C#暧昧通话问题暧昧、问题

2023-09-04 00:54:08 作者:Gg?

我有一个问题,这不是一个真正的问题,但一些让我有点好奇。

I have a question that's not really a problem, but something that made me a little curious.

我有一类在它的两种方法。之一是一个静态方法,另一种是一个实例方法。的方法具有相同的名称。

I have a class with two methods in it. One is a static method and the other one is an instance method. The methods have the same name.

public class BlockHeader
{
    public static BlockHeader Peek(BinaryReader reader)
    {
    	// Create a block header and peek at it.           
    	BlockHeader blockHeader = new BlockHeader();
    	blockHeader.Peek(reader);
    	return blockHeader;
    }

    public virtual void Peek(BinaryReader reader)
    {
    	// Do magic.
    }
}

当我尝试建立我的项目,我得到一个错误说:

When I try to build my project I get an error saying:

的调用不明确的   以下方法或属性:   MyApp.BlockHeader.Peek(System.IO.BinaryReader)'   和   MyApp.BlockHeader.Peek(System.IO.BinaryReader)

The call is ambiguous between the following methods or properties: 'MyApp.BlockHeader.Peek(System.IO.BinaryReader)' and 'MyApp.BlockHeader.Peek(System.IO.BinaryReader)'

我知道方法签名几乎是相同的,但我看不出我怎么可能会调用静态直接从一个实例成员方法。

我假设有一个很好的理由,但没有人知道是什么原因?

I assume that there is a very good reason for this, but does anyone know what that reason is?

推荐答案

的C#设计的一般政策是迫使你指定的地方有潜在的不确定性。在重构工具,允许一到rejig的东西是否是静态的或根本不戴帽子的滴在脸上,这一立场是伟大的 - 尤其是对这样的情况下。你会看到其他许多情况下是这样的(覆盖VS虚拟,新的阴影等)。

The general policy of the C# design is to force you to specify wherever there is potential ambiguity. In the face of refactoring tools that allow one to rejig whether things are static or not at the drop of a hat, this stance is great - especially for cases like this. You'll see many other cases like this (override vs virtual, new for shadowing etc.).

在一般情况下,删除此客房类型的混乱将使C更清晰,并迫使你保持你的房子,以便在$ C $。

In general, removing this type of room for confusion will make the code clearer and forces you to keep your house in order.

编辑:从埃里克利珀好的帖子讨论了另一种原因歧义,导致您看到错误