类中不允许使用同名属性和方法,但允许作为扩展方法,是否有特定原因?

问题描述 投票:0回答:2

当我错误地假设我可以编写一个具有相同命名属性和方法的类时,我正在考虑 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;
    }
}
c# methods properties extension-methods
2个回答
3
投票

我记得 10 年前在 Microsoft 的一个群组中问过这个问题:

http://www.developmentnow.com/g/36_2003_9_0_0_195928/methods-and-properties-of-the-same-name.htm

正如你所看到的,没有令人信服的答案。

这在 CIL 中当然很容易实现,因为属性会转换为

getXX
/
setXX
方法的巴黎。


1
投票

这是因为

Count(this C c)
是一种扩展方法,实际上并不构成类型的一部分。

这意味着您可以在

Count()
+ 扩展
C
中拥有一个方法
Count()
。如果调用它,将被调用实例方法。

因此,如果我们考虑一处房产,问题就更少了。

© www.soinside.com 2019 - 2024. All rights reserved.