我设置了一个简单的程序来测试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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我期待输出
真正!
但我得到的却是
真正!
假!WTF!
这是怎么回事?
Mar*_*ell 10
如果我不得不猜测,我会说调试器运行一次以显示IDE中局部变量的成员.
如果您在属性中有副作用(您不应该这样做),请不要在IDE中运行它:)
在控制台试试吧; 它应该在那里表现自己.
| 归档时间: |
|
| 查看次数: |
209 次 |
| 最近记录: |