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