c# - 调用在以下方法或属性(一个静态和一个非静态)之间不明确

标签 c#

为什么我不允许拥有具有相同签名的静态和非静态方法?

假设我有这样一个类

public class TestClass
{
    public object thing { get; set; }

    public TestClass()
    {

    }

    public TestClass(object thing)
    {
        this.thing = thing;
    }

    public static TestClass ConvertTestClass(object thing)
    {
        return new TestClass(thing);
    }

    public TestClass ConvertTestClass(object thing)
    {
        this.thing = thing;
        return this;
    }

    
}

我试着像这样使用它

public class SomeOtherClass
{
    public SomeOtherClass()
    {
        TestClass tc = TestClass.ConvertTestClass(new object());

        TestClass tc2 = new TestClass();
        tc2.ConvertTestClass(new object());
    }
}

我在 TestClass.ConvertTestClass(new object());

上收到以下错误

The call is ambiguous between the following methods or properties: 'TestClass.ConvertTestClass(object)' and 'TestClass.ConvertTestClass(object)'

以及 tc2.ConvertTestClass(new object()); 上的这些错误

The call is ambiguous between the following methods or properties: 'TestClass.ConvertTestClass(object)' and 'TestClass.ConvertTestClass(object)'

Member 'TestClass.ConvertTestClass(object)' cannot be accessed with an instance reference; qualify it with a type name instead

编译器真的无法区分该方法的静态版本和非静态版本之间的区别,还是我在这里遗漏了什么?

我没有使用 ReSharper(这似乎是其他问题中类似问题的根源)。

最佳答案

它给你一个错误,所以可以肯定的是,编译器不能或不会区分这两种方法。

无论如何执行这种重载可能不是一个好主意,因为不清楚您打算调用哪个方法,但如果这还不够,C# 5 规范定义了这样的方法签名(第 3.6 节):

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.

它没有明确提及 static,但也没有将其作为“签名”定义的一部分。因此,可以公平地假设,根据规范,方法重载不能仅在它是静态的还是实例化的方面有所不同。

关于c# - 调用在以下方法或属性(一个静态和一个非静态)之间不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29638696/

相关文章:

c# - Roslyn:如何获取未解析类型的候选命名空间

c# - 仅在多线程时抛出 StackOverFlowException

c# - 如何使类反序列化为不同的名称

c# - 如何使用 C# 和 asp.net 创建带用户名的子域?

javascript - @Html.TextBoxFor 文本改变事件

c# - 从数据库表中删除行

c# - 对字符串值内的数据进行排序

c# - Android 应用程序 SQLite 的更新如何进行

C# ToolStrip 是透明的但边框仍然可见?

c# - 创建动态控件