Reputation: 7570
I have a class which takes a generic class TState
in its constructor, under the condition that TState
can be converted to a UInt64
using a TypeConverter
. It will then be used as flags.
I want to use a [Flags]
enum for TState
, but even if I define it as
[Flags]
public enum EState : ulong
{
None = 0x0,
State1= 0x1,
State2= 0x2,
State3= 0x4
}
then if TypeConverter typeConv = TypeDescriptor.GetConverter(typeof(EState));
typeConv.CanConvertTo(typeof(UInt64))
is false.
How can I make an enum which will convert appropriately? Thanks!
Upvotes: 3
Views: 2118
Reputation: 81660
You can use Convert.ChangeType()
:
[Flags]
private enum MyEnum1 : ulong
{
A =1,
B = 2
}
And then
MyEnum1 enum1 = MyEnum1.A | MyEnum1.B;
ulong changeType = (ulong) Convert.ChangeType(enum1, typeof (ulong));
Why TypeDescriptor
does not work?
According to docs:
This method looks for the appropriate type converter by looking for a TypeConverterAttribute. If it cannot find a TypeConverterAttribute, it traverses the base class hierarchy of the class until it finds a primitive type.
TypeDescriptor and TypeConvertor work with ExpandableObjectConverter
while Convert
works with IConvertible
.
Upvotes: 2