Why is this test expression an error?

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?

+4
source share
5 answers

You can check if they are the same object using Object.ReferenceEqualsor Object.Equals.

, (IA IB ) , , , .

+11

, 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))?

T X, X IA, obj obj2.

X IA. , - X, ; .

?

, , obj . , , .

, , ! , , T , == , , IA .

, , .

, T , , . T .

+11

(, , ):

, :

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 , .
  • . -, .

T , , . , , T :

static void testFunction<T>(T obj) where T : class, IA, IB
{
    IA obj2 = obj;

    if (obj == obj2) // compiles fine
    {

    }
}
+6

    if (obj.Equals(obj2))

IA ==.

+1

Ahh .

, "" where, .

    static void testFunction<T>(T obj) where T : class, IA, IB
    {
        IA obj2 = obj;

        if (obj == obj2)
        {

        }
    }

, !: -)

0

All Articles