为什么要使用get;并设定;在没有任何争论的财产?

时间:2014-11-26 21:57:59

标签: c# get set setter getter

我最近一直在学习C#书籍,在解释属性之后,我注意到它们使用了像

这样的属性
public int AlertLevel { get; private set; }

我无法弄清楚为什么你会在没有传递任何争论的情况下这样做?感谢您提前获取任何信息。

4 个答案:

答案 0 :(得分:3)

属性实际上是C#中的方法。您在代码中显示的是auto-implemented属性。这是一种合成糖:

// this backing field is generated by compiler
int alertLevel;

public int AlertLevel 
{
   get { return alertLevel; }
   private set { alertLevel = value; }  
}

这是另一个语法糖:

int alertLevel;

public int getAlertLevel()
{
    return alertLevel;
}
private void setAlertLevel(int value)
{
    alertLevel = value;
}

所以你写的代码越来越少,行为也越来越差。这就是重点。编译器会为你付出艰苦的努力。

答案 1 :(得分:0)

他们被称为自动属性。这是语法糖。

相当于:

private int alertLevel;
public int AlertLevel
{
  get { return alertLevel; }
  private set { alertLevel = value; }  
}

它允许从其他类访问该值,但只能在类中设置。

答案 2 :(得分:0)

这样做是为了将元素声明为具有辅助功能设置的可编辑属性,因此设置了private声明。您可以在任何可访问的属性上明确设置get;set;,但效果相同。这只是输入完整getter-setter关系的一种更快捷方式。

答案 3 :(得分:0)

您列出的示例实际上非常方便。如果您不希望其他类能够修改此属性,则这比以下更容易:

private int alertLevel;
public int AlertLevel
{
    get
    {
        return alertLevel;
    }
}

另一件事是Designer视图将识别属性并在IntelliSense中公开它们。