값 동등성과 해시 코드
Coddy의 Kotlin 개발자를 위한 C# 코스 레슨. 48개 중 40번째.
Kotlin의 ==는 equals를 호출하며, 해시 컬렉션에서 hashCode는 일치해야 합니다. C#의 값 동등성에는 IEquatable<T>, Equals 및 GetHashCode를 사용할 수 있습니다. Equals만 재정의해도 ==가 오버로드되지는 않습니다. 정규화된 ASCII 동등성이 해싱과 일관되도록 하세요.
일반 클래스의 참조 동등성은 값 기반 동등성 계약과 다릅니다. IEquatable<T>는 형식이 지정된 동등성 메서드를 제공합니다. 동등한 객체는 동일한 해시 코드를 가져야 해시 컬렉션이 올바르게 동작합니다. 동등성과 해싱에 동일한 비교자를 사용하고, 비교 대상 상태를 안정적으로 유지하세요.
Kotlin 참조 코드
class Tag(val text:String){override fun equals(other:Any?)=other is Tag && text.lowercase()==other.text.lowercase();override fun hashCode()=text.lowercase().hashCode()}
fun main() {
val a=Tag("Tea");val b=Tag("tea")
println(a==b)
println(setOf(a,b).size)
}Main 내부의 C# 문장
Console.WriteLine(StringComparer.OrdinalIgnoreCase.Equals("Tea", "tea") ? "true" : "false");이는 핵심 내용에 초점을 맞춘 교육용 발췌 코드입니다. 과제 파일에는 실행 가능한 전체 래퍼 코드가 포함되어 있으며, 위 스니펫은 관련 선언과 문장만 보여 줍니다.
참조 출력:
true
1C# 출력:
true챌린지
쉬움서수 방식의 대소문자 구분 없는 텍스트 비교를 사용해 Label의 동등성을 구현하세요. 입력을 다듬지 마세요. IEquatable<Label>, object.Equals 및 이에 맞는 GetHashCode를 구현하세요. null 또는 다른 객체 유형과의 동등성은 false여야 합니다.
잠금 해제된 C# 파일을 수정하세요. 표시된 잠금 상태의 Main.cs는 설명된 줄을 읽고, Exercise.Solve를 호출하고, 입력이 변경되지 않았는지 확인한 다음 결과를 마지막 줄바꿈 하나와 함께 출력합니다. 선언된 API를 유지하세요. 두 번째 Main을 추가하거나 진단 출력을 출력하지 마세요.
잠금 상태의 실행기도 Solve 래퍼만 확인하는 것이 아니라, 내보낸 헬퍼 또는 클래스 API를 독립적으로 테스트합니다.
직접 해보기
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");
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Kotlin 개발자를 위한 C#의 모든 레슨
직접 연습해 보세요: 온라인 C# 컴파일러