Twoja metoda rodzajowa będzie w istocie być wykonanie odniesienia sprawdzanie równości - a wartości s1
i s2
odnoszą się do różnych, ale równych strun. Można pokazać to łatwiej tak:
string x = "test";
string y = new string(x.ToCharArray());
Console.WriteLine(x == y); // Use string overload, checks for equality, result = true
Console.WriteLine(x.Equals(y)); // Use overridden Equals method, result = true
Console.WriteLine(ReferenceEquals(x, y)); // False because they're different objects
Console.WriteLine((object) x == (object) y); // Reference comparison again - result = false
pamiętać, że ograniczenie w OpTest
nie zmienia który ==
operator jest używany. To jest określane podczas kompilacji, w oparciu o ograniczenia na T
. Zauważ, że operatorzy nigdy nie są przesłaniany, tylko przeładowany. Oznacza to, że implementacja jest wybierana podczas kompilacji, niezależnie od typu w czasie wykonywania.
Jeśli ograniczyłeś T
, aby wyprowadzić z jakiegoś typu, który przeciąży operator ==
, kompilator użyje tego przeciążenia. Na przykład:
using System;
class SillyClass
{
public static string operator ==(SillyClass x, SillyClass y) => "equal";
public static string operator !=(SillyClass x, SillyClass y) => "not equal";
}
class SillySubclass : SillyClass
{
public static string operator ==(SillySubclass x, SillySubclass y) => "sillier";
public static string operator !=(SillySubclass x, SillySubclass y) => "very silly";
}
class Test
{
static void Main()
{
var x = new SillySubclass();
var y = new SillySubclass();
OpTest(x, y);
}
static void OpTest<T>(T x, T y) where T : SillyClass
{
Console.WriteLine(x == y);
Console.WriteLine(x != y);
}
}
Oto metoda OpTest
ma użyć przeciążone operatory - ale zawsze tylko te z SillyClass
, nie SillySubclass
.
Pomaga spojrzeć na IL, np. używając ildazu do samodzielnego badania tego rodzaju zachowań. – Jeroen
Jeśli chcesz porównać dla równości w kodzie generycznym, użyj 'EqualityComparer .Default.Equals (s, t)' i opcjonalnie pozwól użytkownikowi przekazać własny 'IEqualityComparer '. –
CodesInChaos
Prawdopodobny duplikat [C# różnicy między == i Equals()] (https://stackoverflow.com/questions/814878/c-sharp-difference-between-and-equals) – Dukeling