Value-typed Field of a Reference-typed Argument (C#)

本文通过一个简单的.NET Core示例,探讨了值类型(struct)与引用类型(class)作为方法参数时的行为差异,特别是当修改值类型字段时,原始实例是否受到影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Suppose you have a method, say f, accepts a referenced typed parameter, say a.

The referenced type has a value-typed field, say b.

What if the b changes inside f? Will b changes as well after f for a?

The following code has been used to test the result via .NET Core CLI 2.0.0

using static System.Console;

namespace vf
{
    class Program
    {
        static void Main(string[] args)
        {
        	ReferenceType a = new ReferenceType();
            WriteLine($"Initial value of a.b: {a.b}");
            f(a);
            WriteLine($"After f, value of a.b: {a.b}");
        }
        private static void f(ReferenceType a){
    		a.b++;
    	}
    }
    public struct ReferenceType{
    	public int b;
    }

}

Curious to find that the value-typed field of a reference-typed instance as an argument passed to a method, which takes usual parameters.does not change after the method is called. That is to say, b does not change to 1 as expected.

Then we look back at the definition of value type and reference type again. Only to find a fact that has been negalected ...

A struct type (including user defined struct) is a value type.

Therefore, if we change the definition from struct toclass, everything will work as expected in the assumption ahead.

To achieve the assumption above still with struct definition, we can use ref to introduce the parameter as a reference.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值