Menu
CoddyTech

Igualdade por valor e códigos hash

Lição 40 de 48 do curso C# para desenvolvedores Dart da Coddy.

Os operadores == e hashCode de Dart devem concordar para conjuntos e mapas. Em C#, Equals, IEquatable<T> e GetHashCode precisam da mesma concordância. Em C#, sobrescrever Equals sozinho não redefine ==; mantenha explícitas as comparações por identidade e por valor.

A igualdade por referência de uma classe comum difere de um contrato de igualdade baseado em valor. IEquatable<T> fornece um método de igualdade tipado. Objetos iguais devem ter códigos hash iguais para que coleções hash funcionem corretamente. Use o mesmo comparador para igualdade e hashing e mantenha estável o estado comparado.

Referência de Dart

class Tag { final String text; Tag(this.text); @override bool operator ==(Object other)=>other is Tag && text.toLowerCase()==other.text.toLowerCase(); @override int get hashCode=>text.toLowerCase().hashCode; }
void main() {
print(Tag("Tea") == Tag("tea")); print({Tag("Tea"),Tag("tea")}.length);
}

Instruções de C# dentro de Main

Console.WriteLine(StringComparer.OrdinalIgnoreCase.Equals("Tea", "tea") ? "true" : "false");

Estes são trechos didáticos focados. Os arquivos do desafio incluem estruturas executáveis completas; os trechos acima mostram as declarações e instruções relevantes.

Saída de referência:

true
1

Saída de C#:

true
challenge icon

Desafio

Fácil

Implemente a igualdade de Label usando uma comparação ordinal de texto que não diferencia maiúsculas de minúsculas. Não remova espaços em branco da entrada. Implemente IEquatable<Label>, object.Equals e um GetHashCode correspondente. A igualdade com null ou com um objeto de outro tipo deve ser false.

Edite os arquivos C# desbloqueados. O Main.cs visivelmente bloqueado lê as linhas descritas, chama Exercise.Solve, verifica se a entrada não foi modificada e imprime o resultado com uma quebra de linha final. Mantenha as APIs declaradas. Não adicione um segundo Main nem imprima saída de diagnóstico.

O inicializador bloqueado também testa a API exportada do auxiliar ou da classe de forma independente, não apenas o wrapper Solve.

Experimente você mesmo

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");
}
}
quiz iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de C# para desenvolvedores Dart

Pratique por conta própria: Compilador de C# online