有什么解决方案可以以更好/更短的方式重构以下开关/案例代码?
property.Value 是一个 JTokenopportunity 是CRM Dynamics实体(类似于字典)我尝试了以下方法,但未成功(C#不可接受)
Type target = property.Value.Type.GetType();
opportunity[property.Key] = property.Value.Value<target>();
Run Code Online (Sandbox Code Playgroud)
这是我要简化的代码。(JTokenType.Object并且JTokenType.Array以其他方式处理。)
switch (property.Value.Type)
{
case JTokenType.Boolean:
opportunity[property.Key] = property.Value.Value<bool>();
break;
case JTokenType.Date:
opportunity[property.Key] = property.Value.Value<DateTime>();
break;
case JTokenType.Integer:
opportunity[property.Key] = property.Value.Value<int>();
break;
case JTokenType.String:
opportunity[property.Key] = property.Value.Value<string>();
break;
case JTokenType.Guid:
opportunity[property.Key] = property.Value.Value<Guid>();
break;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过@diiN_的建议:
opportunity[property.Key] = property.Value.Value<dynamic>();
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用以下方法代替switch语句:
if (property.Value is JValue)
{
opportunity[property.Key] = ((JValue)property.Value).Value;
}
Run Code Online (Sandbox Code Playgroud)