当对象包含枚举时,不能使用将字典映射到类型化对象



我需要将Dictionary转换为包含枚举的对象,但我遇到了错误错误:无法转换枚举,我无法修复它

private static T DictionaryToObject<T>(IDictionary<string, string> dict) where T : new()
{
var t = new T();
PropertyInfo[] properties = t.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
if (!dict.Any(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase)))
continue;

KeyValuePair<string, string> item = dict.First(x => x.Key.Equals(property.Name, StringComparison.InvariantCultureIgnoreCase));

// Find which property type (int, string, double? etc) the CURRENT property is...
Type tPropertyType = t.GetType().GetProperty(property.Name).PropertyType;

// Fix nullables...
Type newT = Nullable.GetUnderlyingType(tPropertyType) ?? tPropertyType;

// ...and change the type
object newA = Convert.ChangeType(item.Value, newT);
t.GetType().GetProperty(property.Name).SetValue(t, newA, null);
}
return t;
}

我认为可以使用更简单的方法将字典转换为类型化对象:Newtonsoft.Json NuGet包。

namespace MappingTest
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
var dict = new Dictionary<string, string>
{
{"TestProp1", "TestValue1"},
{"TestProp2", "TestValue2"}
};
var myClass = DictionaryToObject<MyClass>(dict);
Console.WriteLine($"myClass.TestProp1: {myClass.TestProp1}");
Console.WriteLine($"myClass.TestProp2: {myClass.TestProp2}");
}
enum TestValues
{
TestValue1,
TestValue2
}
class MyClass
{
public TestValues? TestProp1 { get; set; }
public TestValues TestProp2 { get; set; }
}
private static T DictionaryToObject<T>(IDictionary<string, string> dict)
{
JObject obj = JObject.FromObject(dict);
return obj.ToObject<T>();
}
}
}

最新更新