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

标签 c# compiler-construction properties methods extension-methods

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

最佳答案

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

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

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

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

关于c# - 是否有特定原因在类中不允许使用同名属性和方法,但允许将其作为扩展方法使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725359/

相关文章:

java - 在java中读取属性文件的有效方法

c# - 在 C# 中模拟 Javascript 'doPostBack()'

c# - 文档的“屏幕截图”

c - 对于 C 开发人员,Clang 版本 2.8 和 3.1 之间有什么实际区别?

python - llvmlite 中的链接 C

c# - 为什么这个 'Label' 是一个字段?

java - Spring 应用程序正在从我的所有属性文件加载属性,而不仅仅是我在上下文 :property-placeholder 中指定的属性

c# - Windows Phone 中不同的大磁贴和中磁贴

c# - 我应该在 DuplexClientBase 构造函数的 "endpointConfigurationName"中指定什么?

c++ - C++ 可变参数模板如何在内部工作