这个想法来自于C#,经常用wpf的话,会接触绑定。数据绑定的实现要点之一便是get与set方法,下面的片段展示了这个事请。如果您想直接带走代码,可以跳转到文章末尾。
namespace GetAndSet
{
class Example
{
private string _x;
public string x
{
get
{
Console.WriteLine("x 取得值");
return _x;
}
set
{
Console.WriteLine("x 设置值");
_x = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Example test = new Example();
test.x = "debug";
Console.WriteLine("----------------");
Console.WriteLine("test.x = " + test.x);
Console.ReadKey();
}
}
}
如果你运行它,会得到:
<