I have a class which takes a generic class TState in its constructor, under the condition that TState can be converted to a UInt64using 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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With