Value Types and Reference Types (C#)

本文探讨了C#中值类型(如struct)与引用类型(如class)的区别。值类型直接在栈上分配,其生命周期局限于定义作用域,而引用类型在堆上分配。当值类型包含引用类型时,赋值操作产生浅拷贝。通过`ref`关键字,方法可以改变引用类型参数的引用,而非仅修改状态。示例展示了`ref`参数如何改变对象实例。

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

C# structs are derived from System.ValueType which overrides the virtual methods in System.Object to use value-based semanitcs instead of reference-based ones.

System.ValueType is allocated on stack rather than on garbage-collected heap. Its lifetime is in the defining scope. Once it runs out of the defining scope, it is popped off the stack. Game over!

int type is a System.Int32 structure.

By default, when a value type contains other reference types (e.g. a struct contains a class), assignment results in a copy of the references (shallow copy).

If a reference type is passed by reference (using ref, the reference is copied by reference), the called method may change the values of the state data and the object it is referencing (i.e. reassign it to a different or new object). 

But if a reference type is passed by value (without modifier, the reference is copied by value), its state value could be changed but not the object being referenced (meaning it is still pointing to the same object on heap).

namespace ConsoleApp11
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public Person(string name, int age)
        {
            Name = name; 
            Age = age;
        }
        public void Display()
        {
            Console.WriteLine($"{Name} {Age}"); 
        }
    }
}

namespace ConsoleApp11
{
    public static class Common
    {
        public static void ChangePerson(ref Person p)
        {
            p.Age = 100;
            p = new Person("Cici", 25);
        }

        public static void ChangePerson(Person p)
        {
            p.Age = 99;
            p = new Person("Lily", 35);
        }
    }
}
using ConsoleApp11;
using static ConsoleApp11.Common;

Person p1 = new Person("Mike", 80);
Console.WriteLine("Original person");
p1.Display();
ChangePerson(p1);
Console.WriteLine("After being passed by value");
p1.Display();
ChangePerson(ref p1);
Console.WriteLine("After being passed by reference");
p1.Display();
Console.ReadLine();

// result:
// Original person
// Mike 80
// After being passed by value
// Mike 99
// After being passed by reference
// Cici 25

 Both value types and reference types can implement interfaces, support fields, method, overloaded operators, constants, properties, and events.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值