从我知道是枚举的动态类型创建枚举变量?
Creating Enum variable from a dynamic type that I know is an Enum?
我有一个 System.Type type
变量,我检查了 type.IsEnum
并返回了 true
。
假设这个type
变量实际上是Direction
枚举,其中有这些枚举:Left, Up, Down, Right
但是前面的代码只知道它是一个枚举。它可能是其他取决于 type
但我们保证它是一个具有 .IsEnum
的枚举
现在,我如何创建这个 type
代表的 Direction
类型的新变量?说,我希望它的值来自整数 0,它应该代表 Left
.
如果你想检查你得到的枚举是 Direction
类型,然后用它做一些事情,你可以使用类型上的 IsAssignableFrom
方法来检查,比如下面的例子:
enum Direction
{
Left = 0,
Up,
Down,
Right
}
public static void DoSomethingIfDirection(object item)
{
if (item != null)
{
Type type = item.GetType();
if (type.IsEnum && typeof(Direction).IsAssignableFrom(type))
{
// Do something
Console.WriteLine((Direction)item);
}
}
}
public static void Main(params string[] args)
{
DoSomethingIfDirection("Hello");
DoSomethingIfDirection("Left");
DoSomethingIfDirection(Direction.Left);
}
Enum.ToObject(Type,object)
解决了这个问题。
例如在我确认type
是一个System.Enum
之后我可以做(System.Enum)Enum.ToObject(type,0)
.
令人困惑,因为尽管名称为 Enum.ToObject
,但此方法将对象转换为枚举,而不是将枚举转换为对象。但也许名称指的是此方法的返回类型,即 object
.
我有一个 System.Type type
变量,我检查了 type.IsEnum
并返回了 true
。
假设这个type
变量实际上是Direction
枚举,其中有这些枚举:Left, Up, Down, Right
但是前面的代码只知道它是一个枚举。它可能是其他取决于 type
但我们保证它是一个具有 .IsEnum
现在,我如何创建这个 type
代表的 Direction
类型的新变量?说,我希望它的值来自整数 0,它应该代表 Left
.
如果你想检查你得到的枚举是 Direction
类型,然后用它做一些事情,你可以使用类型上的 IsAssignableFrom
方法来检查,比如下面的例子:
enum Direction
{
Left = 0,
Up,
Down,
Right
}
public static void DoSomethingIfDirection(object item)
{
if (item != null)
{
Type type = item.GetType();
if (type.IsEnum && typeof(Direction).IsAssignableFrom(type))
{
// Do something
Console.WriteLine((Direction)item);
}
}
}
public static void Main(params string[] args)
{
DoSomethingIfDirection("Hello");
DoSomethingIfDirection("Left");
DoSomethingIfDirection(Direction.Left);
}
Enum.ToObject(Type,object)
解决了这个问题。
例如在我确认type
是一个System.Enum
之后我可以做(System.Enum)Enum.ToObject(type,0)
.
令人困惑,因为尽管名称为 Enum.ToObject
,但此方法将对象转换为枚举,而不是将枚举转换为对象。但也许名称指的是此方法的返回类型,即 object
.