Menu
CoddyTech

值语义与引用语义

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

Python 对象基于引用;dataclasses.replace 会显式创建另一个实例。C# 结构体赋值本身会复制值,这与类赋值不同。这两种模型都不能保证在嵌套字段持有引用时进行深拷贝。

结构体赋值会复制值;类赋值会复制对象的引用。修改复制后的结构体字段不会改变原始对象,而修改别名指向的类对象则会改变它。结构体仍然可以包含引用,因此复制值并不总能实现深拷贝。

Python 引用

from dataclasses import dataclass, replace
@dataclass
class Point:
    x: int
a = Point(2)
b = replace(a, x=9)
print(a.x)

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自我测试

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

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

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