类中为什么不允许同名属性和方法,但扩展方法可以?

3

我当时在考虑List的功能,没有意识到Count()是一个扩展方法,所以错误地假设我可以编写一个具有相同名称属性和方法的类。当时我想要实现的目标是为特定情况下“参数化属性”。

现在我意识到我可以这样做,只要我利用扩展方法即可。

这是有意禁止在类中但允许在扩展中使用,还是一个不存在的功能?

void Main()
{
    var list = new List<string>();

    // You compile code that gets the property named Count
    // and calls the method named Count()
    list.Add("x");
    Console.WriteLine (list.Count);
    list.Add("x");
    Console.WriteLine (list.Count());

    var c = new C();
    Console.WriteLine (c.Count);
    Console.WriteLine (c.Count());
}

public class C
{
    public int Count { get { return 3; } }

    // But you cannot compile a class that contains both a property
    // named Count and a method named Count()
    //public int Count () { return 0; } // <-- does not compile
}

public static class X 
{
    public static int Count(this C c)
    {
        return 4;
    }
}

1
请查看以下链接以获取您问题的第一部分答案:https://dev59.com/h3M_5IYBdhLWcg3wp0wX 和 http://stackoverflow.com/questions/1667808/why-does-the-compiler-find-this-ambiguous。第二部分的答案已经由Tigran提供。 - Dennis
2个回答

3

1
这是因为Count(this C c)是一个扩展方法,实际上并不是类型的一部分。
这意味着你可以在C中有一个方法Count()+扩展Count()。如果你调用它,将被调用实例方法。
所以如果我们考虑一个属性,甚至更少的问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接