【问题标题】:Is there a specific reason same-named properties and methods are disallowed in classes but allowed as extension methods?是否有特定原因在类中不允许使用同名属性和方法,但允许作为扩展方法?
【发布时间】:2012-05-23 17:58:52
【问题描述】:

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


【解决方案1】:

我记得 10 年前在微软的一个小组中问过这个问题:

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

如您所见,没有令人信服的答案。

这在 CIL 中当然很容易实现,因为属性转换为getXX/setXX 方法的巴黎。

【讨论】:

    【解决方案2】:

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

    这意味着您可以在C + 扩展Count() 中拥有一个方法Count()。如果调用它,将调用实例方法。

    因此,如果我们考虑一个属性,那么问题就更少了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多