为何C#中Object类型变量赋值后更新未同步?如何实现同步?
Hey there! Let's clear up the confusion here—your expectation makes sense on the surface, but there's a key detail about how value types and boxing work in C# that's tripping you up.
What's Wrong with Your First Code Snippet?
Let's break down your first example step by step:
object a = 10; object b = a; Console.WriteLine("b :" + b); a = 20; Console.WriteLine("after a updateb :" + b);
Even though object is a reference type, assigning an int (a value type) to it triggers a boxing operation. Boxing wraps the int value inside a brand-new reference-type object. Here's exactly what happens:
object a = 10creates a boxed object containing10, andareferences this object.object b = amakesbpoint to the same boxed object asa.- When you run
a = 20, you're not modifying the existing boxed object's value. Instead, you create a new boxed object with20and updateato reference this new instance. The original boxed object (with10) is still referenced byb, sobstays at10.
Your second snippet with raw int values behaves as you expect—value types are copied on assignment, so changing a doesn't affect b. The first snippet is different, but not in the way you assumed, because boxing creates new objects every time you assign a different int to the object variable.
How to Achieve Synced Variable Updates
To make changes to a automatically reflect in b, you need a mutable reference-type container to hold your integer value. This way, both a and b reference the same container object, and modifying the value inside the container will be visible to all references.
A simple custom wrapper class works perfectly here:
// Define a mutable wrapper for integer values public class IntHolder { public int Value { get; set; } } // Usage example IntHolder a = new IntHolder { Value = 10 }; IntHolder b = a; Console.WriteLine("b : " + b.Value); // Output: b : 10 a.Value = 20; Console.WriteLine("after a update b : " + b.Value); // Output: after a update b : 20
In this case, a and b both point to the same IntHolder instance. When you update a.Value, you're modifying the value inside that single shared object—so b sees the change immediately, since it's referencing the same container.
Quick Recap
- Boxing a value type creates a new reference-type instance every time you assign a different value to the
objectvariable. - To sync updates across variables, use a mutable reference type (like a custom class) to hold the value, so all variables reference the same instance.
内容的提问来源于stack exchange,提问作者Muhammad Faizan Khan

