C#中继承类重写基类属性值失败:赋值未生效问题
Hey there, let's dig into why modifying this.config in class A isn't working—this is a classic gotcha with how your base class B is implementing the config property.
The Root Cause
Look at the config property in class B:
public configObject config { get { var config = new configObject { property1 = value1; property2 = value2; property3 = null; property4 = false; }; return config; } set { this.config = value; } }
Every single time you access this.config, the getter creates a brand new configObject instance with the default values. So when you try to update a field like this.config.property3 = "something", you're actually modifying a temporary instance that gets thrown away immediately. The next time you access this.config, you get a fresh new object with the original defaults—hence your changes never stick.
On top of that, the setter has a critical bug: this.config = value will trigger an infinite recursion (it calls the setter over and over until your stack overflows). Oops.
The Fix
We need to make class B hold onto a single, persistent configObject instance instead of creating a new one every time. Here's how to adjust class B:
public class B { // Private field to store the actual config instance private configObject _config; public configObject config { get { // Lazy-load the config: only create it once, when first accessed if (_config == null) { _config = new configObject { property1 = value1, property2 = value2, property3 = null, property4 = false }; } return _config; // Return the same instance every time } set { _config = value; // Assign directly to the private field to avoid recursion } } }
Now, when you access this.config in class A, you're always getting the same instance. Any changes you make to its fields will persist because you're modifying the actual stored object, not a throwaway temp.
Using It in Class A
Your class A can now modify the config fields normally, and the changes will stick:
public class A: B { public A() { // Example updates that will actually persist this.config.property3 = "my custom value"; this.config.property4 = true; } public string configJson { get { // Now this will serialize the updated config instance return JsonSerializer.Serialize(this.config); } } }
Extra Tips
- If you ever need to reset the config to default values, add a method to class B like
public void ResetConfig() => _config = null;—the next time you accessconfig, it'll reinitialize with defaults. - If
configObjectis a struct instead of a class, you'll need to handle it differently (since structs are value types), but based on your code it looks like a class, so the above should work.
内容的提问来源于stack exchange,提问作者AlreadyLost

