Menu
CoddyTech

值语义与引用语义

Coddy 面向 C++ 开发者的 C# 课程的第 30 课,共 48 课。

C++ 类对象具有值复制语义,除非通过引用或指针访问。C# 结构体会复制值,但 C# 类变量会复制引用。C++ 的 class 关键字并不意味着赋值行为与 C# 的 class 关键字相同。

结构体赋值会复制值;类赋值会复制对对象的引用。修改复制后的结构体字段不会改变原对象,而修改被别名引用的类对象会改变原对象。结构体仍然可以包含引用,因此值复制并不总是深度克隆。

C++ 引用

#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
struct Point { int x; };
int main() {
Point a{2};
Point b=a; b.x=9;
cout << a.x << "\n";
}

C# 辅助声明

struct Point { public int X; public Point(int x) { X = x; } }

Main 中的 C# 语句

Point a = new Point(2);
Point b = a; b.X = 9;
Console.WriteLine(a.X);

这些是用于讲解的精简代码片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。

引用输出:

2

C# 输出:

2
challenge icon

挑战

简单

使用提供的 Point 结构体和 Box 类。复制这个点,并且只将副本更改 change 的值。为一个 box 创建别名,并将它更改相同的值。按逗号分隔的整数形式返回 originalPoint,changedPoint,originalBox。

编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述的行,调用 Exercise.Solve,验证输入未被修改,并在结果末尾打印一个换行符。保留已声明的 API。不要添加第二个 Main,也不要打印诊断输出。

亲手试试

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);

var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C++ 开发者的 C#中的所有课

自己练习: C# 在线编译器