简体   繁体   中英

Dictionary<string, object> to strongly typed object

I need a way to convert a Dictionary to a strongly typed object. Im aware that I could use reflection and simply create a new object of the type I want and then just iterate through the properties and assign them.. basically.. https://dotnetfiddle.net/yz9GPd

However.. this seems to me to be super inefficient.. so is there any good way to improve this?.. and also a way to use less reflection (since thats usually quite costly). Maybe some way to do this using Compiled Expressions/Functions?

You could use something like FastMember which is using Reflection.Emit to map to the members of your class with their names as strings. It's fast compared to standard reflection, but difficult to write if you're doing it yourself.

Using that library, your example would look like this:

Dictionary<string, object> values = new Dictionary<string, object>()
{
    { "Property1", "MyValue" },
    { "Property2", 1234 },
    { "Property3", true },
};

MyType myType = new MyType();
var accessor = TypeAccessor.Create(typeof(MyType));
foreach (var entry in values)
    accessor[myType, entry.Key] = entry.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM