值语义与引用语义
Coddy 面向 Dart 开发者的 C# 课程的第 30 课,共 48 课。
Dart 中的类赋值会共享对象引用。C# 中的类赋值也会创建别名,但 struct 会按值复制。Dart 的记录具有结构化的值行为,但它们不是具有相同更新规则的可变 C# struct。
struct 赋值会复制值;类赋值会复制对象的引用。修改复制后的 struct 字段不会改变原值,而修改通过别名引用的类对象则会改变原对象。struct 仍然可以包含引用,因此按值复制并不总是深度克隆。
Dart 引用
class Box { int value; Box(this.value); }
void main() {
final a = Box(2); final b = a; b.value = 9; print(a.value);
}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);这些是用于教学的精简代码片段。挑战文件中包含完整的可执行包装代码;上面的代码片段展示了相关声明和语句。
引用类型的输出:
9C# 的输出:
2挑战
简单使用提供的 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Dart 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器