我设置了一个简单的程序,只是为了测试get访问器中的代码是如何执行的(因为我在另一个项目中遇到了一些问题),并发现了一些非常奇怪的东西:
class Program
{
static void Main(string[] args)
{
var test = new TestClass();
var testBool = test.TestBool;
}
}
public class TestClass
{
private bool _testBool = true;
public bool TestBool
{
get
{
if (_testBool)
{
Console.WriteLine("true!");
}
else
{
Console.WriteLine("false! WTF!");
}
_testBool = false;
return _testBool;
}
}
}
我预计输出为
true!
但我得到的却是
true!
false! WTF!
这是怎么回事?