简体   繁体   中英

Dictionary<string, object> to object

What the best way convert this dictionary:

Dictionary<string, object> person = new Dictionary<string, object>();
                            person.Add("ID", 1);
                            person.Add("Name", "Alex");

to object:

public class Person
{
public int ID{get;set;}
public string Name{get;set;}
}

?

Here is my suggestion:

var newPerson = new Person 
    { 
        ID = (int)person["ID"],
        Name = person["Name"].ToString()
    };

This has no error handling and is assuming that the fields exists in the dictionary and are filled with valid values!

If you want to be able to do this for any object in general, you could use reflection. Assuming the values in the dictionary are the appropriate type and requires no conversion:

static T GetObject<T>(Dictionary<string, object> dict)
    where T : new()
{
    var obj = new T();
    foreach (var property in typeof(T).GetProperties())
    {
        var args = new object[1];
        var setter = property.GetSetMethod(); // property has a public setter
        if (setter != null && dict.TryGetValue(property.Name, out args[0]))
            setter.Invoke(obj, args);
    }
    return obj;
}

Then to use it:

var alexDict = new Dictionary<string, object>
{
    { "ID", 1 },
    { "Name", "Alex" },
};
var alexPerson = GetObject<Person>(alexDict);
Person myPerson = new Person();
myPerson.ID = (int)person["ID"];
myPerson.Name = (string)person["Name"];

Provides no error checking with the int cast.

The easy way:

var person = new Person
{
    Id = (int)dict["ID"],
    Name = (string)dict["Name"]
}

The generic way: use reflection.

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