Fish in the river

思考 技术
记录 回忆
  1. Main page
  2. 软件开发
  3. C#
  4. Main content

值类型和引用类型

2025年3月15日 39hotness 0likes 0comments

不管是面向对象还是面向过程编程。值类型和引用类型都是必须理解的基础概念。

如以下C#代码

using System;

struct Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return $"Point(X: {X}, Y: {Y})";
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public override string ToString()
    {
        return $"Person(Name: {Name}, Age: {Age})";
    }
}
class Program
{
    static void Main(string[] args)
    {
        Point p = new Point(10, 20);
        PrintPoint(p);
        Console.WriteLine($"Point coordinates: X = {p.X}, Y = {p.Y}");
        Person person = new Person("John Doe", 30);
        PrintPerson(person);
        Console.WriteLine($"Person details: Name = {person.Name}, Age = {person.Age}");
    }
    static void PrintPoint(Point point)
    {
        point.X = 1000;
        point.Y = 2000;
        Console.WriteLine($"Point coordinates: X = {point.X}, Y = {point.Y}");
    }

    static void PrintPerson(Person person)
    {
        person.Name = "Joey Yu";
        person.Age = 40;
        Console.WriteLine($"Person details: Name = {person.Name}, Age = {person.Age}");
    }
}

以上代码运行之后,你就会发现结构类型(值类型)和类类型(引用类型)的不同之处。

大家都是先构造了一个实例,p和person。再分别通过PrintPoint和PrintPerson方法传入这个实例进行了重新赋值。

在方法中显示了一下各个实例的属性值。毫无疑问,在方法中打印出来的值 ,都是在方法中重新设置的值。但是在方法执行完成后,再分别打印这两个实例的属性值会发现。结构体的属性值还是原来的那个属性值。而结构体的值通过方法执行后,成为执行之后的值。

结论应该是在结构体实例做为参数传递到方法中的时候,这个结构体复制了一遍。不影响原来的结构体。而类实例做为参数传递到方法中的时候,只是将类的引用标签传递到了方法体中。在方法体中对类的实例的操作,都会影响原来的类的实例。

Tag: C#
Last updated:2025年3月15日

joey

This person is a lazy dog and has left nothing

Like
< Last article

Comments

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
Cancel

归档

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024

分类目录

  • C#
  • Dock
  • Excel
  • Kindle
  • Linux
  • Windows
  • 生活感悟
  • 群晖
  • 运维技术

COPYRIGHT © 2024 水中小鱼. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang