将字典转换为对象模型

时间:2021-03-10 06:46:21

标签: c#

我有一个字典(类似)对象,带有字段名称和字段值。我已经为许多不同的实体定义了模型。我在下面列出了其中之一。但是,我无法为这个模型显式编码,我想创建通用代码,将实体模型转换为人员模型或任何其他类型的模型。这个想法是它可以是任何模型,但是我会在执行时知道哪个。

为了减少代码,我想根据字典中的值映射这些,而不是明确标识每个字段。目标涉及 100 个模型,因此您可以看到它将如何大大减少代码和工作量。我希望能够仅从这个定义中构建模型对象,而不是映射每个字段。

来源

public class EntityModel
{
     public string fieldname { get; set;}
     public string fieldvalue { get; set;}
}

public class ListEntityModel
{
     public list<EntityModel> list {get;set;}

     public string GetValue ( string fname )
     {
           foreach(var em in list )
           {
                 if (em.fieldname == fname) return em.fieldvalue;
           }
           return "";
     }
}

目的地

public class PersonModel {
     public string id { get;set; }
     public string name { get;set;}
     public string manyotherfields { get;set; }
}

大致的工作原理

public PersonModel Transformer(ListEntityModel lem) {
    

}

无聊的方式

public PersonModel TransformMeToModel(ListEntityModel lem) {
   var model =  new PersonModel
   {
       id = lem.GetValue("id"),
       name = lem.GetValue("name"),
       manyotherfields = lem.GetValue("manyotherfields")
   };
   return model;
}


2 个答案:

答案 0 :(得分:2)

你可以使用反射:

.sheet(item: $selectedCategory) { category in
    CommentsView(category: category)
}

但请注意,当您的 public T TransformMeToModel<T>(ListEntityModel lem) { var model = Activator.CreateInstance(typeof(T)); foreach(var entry in lem.list) { model.GetType().GetProperty(entry.fieldname).SetValue(model, entry.fieldvalue); } return (T)model; } 与目标类型的属性(名称或类型)不匹配时,会引发异常。此外,您的目标类需要一个默认构造函数。

在线演示:https://dotnetfiddle.net/fHBJlh

答案 1 :(得分:2)

public class PersonModel
{
    public string id { get; set; }
    public string name { get; set; }
    public string manyotherfields { get; set; }
}
public static T TransformMeToModel<T>(Dictionary<string, string> lem) where T : new()
{
    T t = new T();

    foreach (var p in typeof(T).GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
    {
        if (lem.TryGetValue(p.Name, out string v))
        {
            p.SetValue(t, v);
        }
    }

    return t;
}
var props = new Dictionary<string, string> { { "id", "1" },  {"name", "one" }, { "manyotherfields", "m" } };

var instance = TransformMeToModel<PersonModel>(props);