I want to understand why C # decided to make this test expression an error.
interface IA { } interface IB { } class Foo : IA, IB { } class Program { static void testFunction<T>(T obj) where T : IA, IB { IA obj2 = obj; if (obj == obj2) //ERROR { } } static void Main(string[] args) { Foo myFoo = new Foo(); testFunction(myFoo); Console.ReadLine(); } }
In testFunction, I can make an object named obj2 and not specify it obj without casting it. But why can't I check the two objects to make sure they are the same without casting it? Obviously, they implement the same interface, so why is this a mistake?
You can check if they are the same object using Object.ReferenceEqualsor Object.Equals.
Object.ReferenceEquals
Object.Equals
, (IA IB ) , , , .
IA
IB
, T X, IA.
static void testFunction<T>(T obj) where T : IA { IA obj2 = obj; if (obj == obj2) //ERROR
do testFunction<X>(new X(whatever))?
testFunction<X>(new X(whatever))
T X, X IA, obj obj2.
X IA. , - X, ; .
?
, , obj . , , .
, , ! , , T , == , , IA .
, , .
, T , , . T .
(, , ):
, :
Guid g = Guid.NewGuid(); // a value type object o = g; if (o == g) // ERROR { }
# (Β§7.10.6):
:bool operator ==(object x, object y);bool operator !=(object x, object y);[...]:, null. , (Β§6.2.4) .- T, T - , - null. , T .[...], . :[...]. , struct , .. -, .
:
bool operator ==(object x, object y);
bool operator !=(object x, object y);
[...]
null
T
, . :
T , , . , , T :
static void testFunction<T>(T obj) where T : class, IA, IB { IA obj2 = obj; if (obj == obj2) // compiles fine { } }
if (obj.Equals(obj2))
IA ==.
Ahh .
, "" where, .
static void testFunction<T>(T obj) where T : class, IA, IB { IA obj2 = obj; if (obj == obj2) { } }
, !: -)