简体   繁体   中英

Compare two objects that contain enum values of the same enum type

I have an enum type defined: EnumType Now imagine

object A = EnumType.Value1;
object B = EnumType.Value2;

I would like to make the comparison ( A == B ) give me the correct result independent of the type of Enum used. In the comparison, the object will always contain enums, and both will be of the same type.

How can I achieve this?

There is a good article on MSDN on when to use == and when to use Equals.

Basically there are 2 types of equality: Reference equality and value equality. If 2 objects have reference equality they hence therefore also have value equality (both references point to the same object so of course their values are the same).

The opposite, (and in your case) is not always true though. If 2 objects have value equality they don't necessarily have reference equality. In your case == is acting as reference equality.

  • Usually what you want is Equals , it is a virtual method defined in System.Object.

  • What you usually don't want for reference types is == , it usually compares whether two references refer to the same object.

In your case A and B are boxed into 2 different objects. A refers to the first and B refers to the second. == is testing and seeing that both are referring to different things.

Just use A.Equals(B) , it will call the inner type Equals.

In your case you cannot use == because A and B are boxed in 2 different objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM