How to get flag enumeration for conversion to UInt64 using TypeConverter

I have a class that accepts a generic class in its constructor TState, provided that it TStatecan be converted to UInt64with TypeConverter. Then it will be used as flags.

I want to use an enumeration [Flags]for TState, but even if I define it as

[Flags]  
public enum EState : ulong
{
    None = 0x0,
    State1= 0x1,
    State2= 0x2,
    State3= 0x4
}

then if itโ€™s TypeConverter typeConv = TypeDescriptor.GetConverter(typeof(EState)); typeConv.CanConvertTo(typeof(UInt64))wrong.

How can I make an enumeration that will convert correctly? Thank!

+3
source share
1 answer

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));

UPDATE

Why TypeDescriptordoesnโ€™t work?

According to the docs:

, TypeConverterAttribute. TypeConverterAttribute, , .

TypeDescriptor TypeConvertor ExpandableObjectConverter, Convert IConvertible.

+2

All Articles