我试图采取一些json输入和解析到正确的枚举类型。我有3种枚举类型:解析一个字符串到一个泛型枚举类型
public class Enums
{
public enum Motivators{
Small_Motivator,
Medium_Motivator,
Large_Motivator
}
public enum Reactors{
Small_Reactor,
Large_Reactor
}
public enum Movers{
Small_Mover,
Large_Mover
}
}
我有,需要一个通用的枚举类型,分析检查,我们有哪些类型的方法。
private void InitializeGenerator(Enum enumType)
{
if (enumType is Enums.Motivators)
{
// work work work work work
}
else if (enumType is Enums.Reactors)
{
// work
}
else if (enumType is Enums.Movers)
{
// work
}
else
{
// we dont know what it is
}
}
我的JSON会是这个样子..
{
"WorkerType":"Small_Motivator"
}
然后试图解析JSON ..
JObject jObject = JObject.Parse(json);
JToken worker = jObject.GetValue("WorkerType");
Enum workerType = (Enum)Enum.Parse((typeof(Enum)), worker.ToString(), true);
InitializeGenerator(workerType);
引发以下错误:
An exception of type 'System.ArgumentException' occurred in mscorlib.dll but was not handled in user code
Additional information: Type provided must be an Enum.
当你解析''WorkerType'的值时,你已经期望它是来自'WorkerType'枚举的值,对吗?那么为什么你不使用'Dictionary'从属性到相应的枚举类型呢? – PoByBolek