You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C#中Object类型变量赋值后更新未同步?如何实现同步?

Understanding Why Your Object Assignment Isn't Syncing, and How to Fix It

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:

  1. object a = 10 creates a boxed object containing 10, and a references this object.
  2. object b = a makes b point to the same boxed object as a.
  3. When you run a = 20, you're not modifying the existing boxed object's value. Instead, you create a new boxed object with 20 and update a to reference this new instance. The original boxed object (with 10) is still referenced by b, so b stays at 10.

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 object variable.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:01:08