我正在学习c#。我想知道,为什么
public class Example {
public int X { get; set}
}
使用,当您可以使用时
public class Example {
public int X;
}
根据我的理解,两者都做同样的事情。两者都允许您更改变量的值。为什么只在声明变量public
时使用get / set?
获取器和设置器的目的是在更改或访问属性时进行一些计算,处理或更新。
将getter和setter声明为空与声明公共字段相同。
class Property {
private bool enabled = false;
private int numberOfEnabledReadings = 0;
public bool Enabled {
get
{
//Do some processing (in this case counting the number of accecess)
numberOfEnabledReadings++;
return enabled;
}
set
{
enabled = value;
//Update GUI
}
}
}
看看以下资源
https://www.w3schools.com/cs/cs_properties.asp
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
基本上,属性使您可以指定类的对象如何操作和/或访问其私有变量。