值相等性与哈希码
Coddy 面向 C++ 开发者的 C# 课程的第 40 课,共 48 课。
C++ 的 operator== 和哈希自定义,与 C# 的 Equals/GetHashCode 一样,都需要保持一致。C# 的 IEquatable<T> 提供了类型化的相等性 API,相等的值必须具有相同的哈希值。在此比较中使用 ASCII 标签,可以避免对 Unicode 大小写转换的假设不一致。
普通类的引用相等性不同于基于值的相等性约定。IEquatable<T> 提供了类型化的相等性方法。相等的对象必须具有相同的哈希码,这样哈希集合才能正常工作。相等性比较和哈希计算要使用相同的比较器,并确保被比较的状态保持稳定。
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;
int main() {
string left="Tea",right="tea";
transform(left.begin(),left.end(),left.begin(),[](unsigned char c){return static_cast<char>(tolower(c));});
cout << (left==right?"true":"false") << "\n";
}
C# Main 中的语句
Console.WriteLine(StringComparer.OrdinalIgnoreCase.Equals("Tea", "tea") ? "true" : "false");这些是用于重点讲解的代码片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。
参考输出:
trueC# 输出:
true挑战
简单使用按序号、不区分大小写的文本比较来实现 Label 的相等性。不要去除输入两端的空白。实现 IEquatable<Label>、object.Equals 和匹配的 GetHashCode。与 null 或其他对象类型比较时,结果必须为 false。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述行,调用 Exercise.Solve,验证输入未被修改,并在末尾输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。
锁定的启动器还会独立测试导出的辅助函数或类 API,而不仅仅是 Solve 包装函数。
亲手试试
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 = input[0]; string before0=Snapshot(a0);
var a1 = input[1]; string before1=Snapshot(a1);
var l1 = new Label("Tea"); var l2 = new Label("tea"); if (!l1.Equals(l2) || !l1.Equals((object)l2) || l1.GetHashCode() != l2.GetHashCode() || l1.Equals((Label)null) || l1.Equals("Tea")) throw new Exception("Equality API");
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 ? "true" : "false");
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 C#中的所有课
自己练习: C# 在线编译器