c# - 如何使用 TypeConverter 获取标志枚举以转换为 UInt64

标签 c# enums type-conversion flags uint64

我有一个类在其构造函数中采用通用类 TState ,条件是 TState 可以转换为 UInt64 使用一个 TypeConverter。然后它将用作标志。

我想为 TState 使用 [Flags] 枚举,但即使我将其定义为

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

然后如果 TypeConverter typeConv = TypeDescriptor.GetConverter(typeof(EState)); typeConv.CanConvertTo(typeof(UInt64))为假。

我怎样才能制作一个可以适当转换的枚举?谢谢!

最佳答案

您可以使用Convert.ChangeType():

[Flags]
private enum MyEnum1 : ulong 
{
   A =1,
   B = 2
}

然后

MyEnum1 enum1 = MyEnum1.A | MyEnum1.B;
ulong changeType = (ulong) Convert.ChangeType(enum1, typeof (ulong));

更新

为什么 TypeDescriptor 不起作用?

根据文档:

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 和 TypeConvertor 与 ExpandableObjectConverter 一起使用,而 ConvertIConvertible 一起使用。

关于c# - 如何使用 TypeConverter 获取标志枚举以转换为 UInt64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5949820/

相关文章:

java - 在 JUnit 参数化测试中使用枚举的所有值

python-3.x - 在 Python 中将 RGBA 转换为 RGB

c# - 在 MVVM (WPF) 应用程序中更改 ListView 上的筛选器后如何滚动到 View ?

swift - 我可以扩展 Swift 保留字 "enum"吗?

java - startActivityForResult 带有枚举

java - 字符串到整数解析中的数字格式异常

types - 戈朗 : Export C fields to be externally visible using CGo

c# - 合并msi和exe

c# - 获取每个连接的带宽统计信息

c# - 执行应用程序所需的库 'hostpolicy.dll'