【问题标题】:Prop and field? [duplicate]道具和场地? [复制]
【发布时间】:2013-09-30 01:44:22
【问题描述】:

What is the difference between a Field and a Property in C#?

我已经阅读了上面的这个主题,但它充满了令人困惑的答案。

我想知道,用简单的英语,这段代码是在字段或属性下面吗? .如果是字段,什么是属性?如果是属性,什么是字段?

class Door
{
     public int width { get; set; }
}

非常感谢。

【问题讨论】:

  • 这是一个属性。如果是public int width;,那就是一个字段。
  • 接受的答案中的 cmets 对您没有帮助吗?
  • 除了 SO 之外,您还查看过其他资源吗?
  • getter 和 setter 表示一个属性。
  • @minitech 将此作为答案发布,因此我可以选择您作为选择的答案:)

标签: c# oop


【解决方案1】:

属性只是为字段定义 getter 和 setter 的语法。

class Door
{
     public int width { get; set; }
}

类似于

class Door
{
    private int width;

    public int getWidth()
    {
        return width;
    }
    public void setWidth(int i)
    {
        width = i;
    }
}

【讨论】:

    【解决方案2】:

    这是一个属性。它是使用 getter、setter 和支持变量创建属性的简写。

    class Door
    {
         public int width { get; set; }
    }
    

    支持变量是匿名的,但编译器为此生成的代码基本上与以下内容相同:

    class Door {
    
      private int _width;
    
      public int width {
        get {
          return _width;
        }
        set {
          _width = value;
        }
      }
    
    }
    

    字段只是类或结构中的公共变量,如下所示:

    class Door {
    
      public int width;
    
    }
    

    在这种情况下,编译器不会创建任何代码来处理该字段,它只是一个普通变量。

    【讨论】:

    • 看不到太多带有同行花括号的 c# 代码。我喜欢它。
    • 实用问题:您在实际项目中使用公共字段吗?现在我可以看到他们对禁令的宗教感情。
    • @IlyaIvanov 我的老师说字段是幼儿园级别的。在现实生活中,您只使用属性。
    • @ÖmerÖzkan:是的,我记得幼儿园级别的 C# 中的字段。美好的过去。 (但说真的——我使用字段,我希望这是现实生活。)
    • @minitech 如果您在我的问题下方发布了您的第一条评论作为答案,我会选择您作为最佳答案。因为它对我最有帮助。为什么不做呢?
    猜你喜欢
    • 2020-08-31
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多