开发者

Why is the == operator (defined for the concrete type) not used?

开发者 https://www.devze.com 2023-03-01 04:38 出处:网络
I have a list defined as: var Items = new List<IItem>(); Now there are a number of different classes that have that interface and one of them is Consumable.The Consumab开发者_运维百科le class

I have a list defined as:

var Items = new List<IItem>();

Now there are a number of different classes that have that interface and one of them is Consumable. The Consumab开发者_运维百科le class also has the == operator overloaded. Now I have the following code and is not working:

if(item1 == item2)
{
    //code...
}

This does not work. I put a break point in the == operator overload and it never gets to it. When I go through line-by-line debugging, both item1 and item2 are of type Consumable, both GetType returns Consumable. I even try this code:

var temp = item1.GetType();
var temp2 = item2.GetType();
if (temp == temp2)
{
    //code...
}

and this equality results is true. Now if I try this:

if(((Consumable)item1) == ((Consumable)item2))
{
    //code...
}

and this triggers the break point in the == operator overload. Why would I have to manually cast the variable if when line-by-line debugging show it already thinks they are both consumable? Is it because I am pulling them from a list of IItems?


Since your list is List<IItem>, I'm assuming you have something like:

var item1 = Items[0];

or whatever; here item1 the variable is typed as IItem. Operator resolution happens during build via static analysis (not at runtime via polymorphism/RTTI), so the only == available is the default for any object, i.e. reference equality.

To support your custom operator, the variables must be typed accordingly, for example:

Consumable item1 = ..., item2 = ...;

Your cast achieves a similar thing.

Another option would be to make sure that == and Equals (and GetHashCode()) are in agreement, and use:

if(Equals(item1, item2)) {...}

which will do null checks and then use your overridden Equals method. This then supports polymorphism, so it doesn't matter what the types are.


The common langauge runtime does only know that your two objects implement the interface IItem. The smallest common part in object hierarchy is System.Object. And you did not overload the == operator of System.Object.

To use the correct overload you have to state the type of the object.


== does not check type equality, but for classes it checks reference equality. So if the variables are pointing to the same object it will be true. For example like this:

var temp = item1;
var temp2 = item1;

if( temp == temp2 )
{
  //this code will execute
}


Shouldn't be the IItem IComparable?

0

精彩评论

暂无评论...
验证码 换一张
取 消