We all know that the "|" symbol can be used in C # to enumerate flags and perform operations. (In fact, this can also be done without the flags enumeration, because "|" is a binary and operation, and any enumeration can be converted to a number .). However, the "|" operation is usually performed when the enumeration type is known, for example:
Fileattributes.System| Fileattributes.Hidden
To perform implicit type and operation, you must convert the enumerated values to numbers in a unified manner, then perform binary and operation, and then convert the enumerated values back to the enumerated type. Note: You can directly convert a number to a known Enumeration type, but you cannot convert the number to an Enum object because the enum object type is unknown. The required method is enum. toobject. It can convert a number to an Enum object of the specified type. It has two parameters: the first is the enumeration type (type object), and the second is the number (INT, uint, long, ulong ...). Its second parameter also has an object type overload, but in fact it is to check whether the object is of the corresponding numeric type, and then call the corresponding type of toobject method.
In this case, we can define an implicit type of flags enumeration and perform the following operations:
Static EnumCombine (TypeEnumtype,Params Enum[] Enums)
{
// Parameter verification
If(Enumtype= Null)
Throw New Argumentnullexception("Enumtype");
If(Enums= Null)
Throw New Argumentnullexception("Enums");
If(!Enumtype.Isenum)
Throw New Argumentexception("Enumtype is not an enumeration type");
If(Enums.Length= 0)
Throw New Argumentexception("Enums does not contain any member");
// Convert the value to long
var longval = convert . toint64 (enums [ 0 ]);
for ( int I = 1 ; I enums . length; I ++ )
Longval=Longval| Convert.Toint64 (enums [I]);
Return(Enum)Enum.Toobject (enumtype, longval );
}
Perform a simple test and define a flags enumeration:
[Flags]
Enum Myenum
{
A= 1, B= 2, C= 4
}
Run:
VaREnumvalue=Combine (Typeof(Myenum),Myenum.B,Myenum.C );
Console.Writeline (enumvalue );
Output:
B, c