我主要是一名C++开发人员,但最近我在使用C#开发一个项目。今天我在使用对象初始化器时遇到了一些意外的行为,至少对我来说是这样。我希望这里有人能够解释一下发生了什么。
示例A
public class Foo {
public bool Bar = false;
}
PassInFoo( new Foo { Bar = true } );
示例 B
public class Foo {
public bool Bar = true;
}
PassInFoo( new Foo { Bar = false } );
示例A按预期工作。传递给PassInFoo的对象具有Bar设置为true。然而,在示例B中,即使在对象初始化程序中分配了false,foo.Bar也被设置为true。是什么导致示例B中的对象初始化程序似乎被忽略?