代码之家  ›  专栏  ›  技术社区  ›  djdd87

为什么类不能有静态或常量属性和同名的实例属性?

c#
  •  7
  • djdd87  · 技术社区  · 14 年前

    我以前从未真正质疑过这个问题。我有一个带有许多字段的输入模型,我想通过输入模型显示属性的字符串名称,以便我的网格可以使用它们:

    public class SomeGridRow
    {
        public string Code { get;set; }
        public string Description { get;set; }
    
        public const string Code = "Code";
    }
    

    显然,这会产生错误:

    类型“somegridrow”已经 包含“代码”的定义

    为什么clr不能处理两个同名的属性,在我看来,它们是分开的?

    string code = gridRow.Code;          // Actual member from instantiated class
    string codeField = SomeGridRow.Code; // Static/Const
    

    我现在只是在用一个叫做 Fields 现在在我的输入中,我可以使用 SomeGridRow.Fields.Code . 有点乱,但还是可以用的。

    4 回复  |  直到 14 年前
        1
  •  7
  •   Nick Craver    14 年前

    public class SomeGridRow
    {
      public string Code { get;set; }
      public const string Code = "Code";
      public void MyMethod() {
        var thing = Code; //what would this reference?
      }
    }
    

    public class SomeGridRow
    {
      public string Code { get;set; }
      public void MyMethod() {
        var thing = Code; //what would this reference?
      }
    }
    

    public class SomeGridRow
    {
      public const string Code = "Code";
      public void MyMethod() {
        var thing = Code; //what would this reference?
      }
    }
    

        2
  •  3
  •   Oded    14 年前

        3
  •  1
  •   Jagmag    14 年前

        4
  •  0
  •   Jon Hanna    14 年前

    string.Empty "abc".Empty

    this