mercredi 26 janvier 2022

How to set Dictionary

If the model has a Dictionary<string, string> property, I want to set values with reflection.

My model is as below,

 public class DataModel
 {
     public string Key { get; set; }

     public Dictionary<string, string> Values { get; set; }
 }

I call the GetModelData method as follows,

row.GetModelData<DataModel>();
private static T GetModelData<T>(this RowModel row) where T : new()
{
    var data = new T();

    List<PropertyInfo> propertyList = typeof(T).GetProperties().ToList();

    PropertyInfo propertyDictionary = propertyList.Where(x => x.PropertyType.Name == typeof(Dictionary<string, string>).Name).FirstOrDefault();

    foreach (var cell in row.Cells)
    {
        if (propertyDictionary != null)
        {
             propertyDictionary.GetType().GetProperty("Item").SetValue(propertyDictionary, cell.X, new[] { cell.Y });
        }
    }

    return data;
}

I'm getting an error here because GetProperty("Item") returns null. But when I create an instance of Dictionary<string, string> and replace propertyDictionary, GetProperty("Item") is not return null and GetModelData method works. What is the difference between them? How can I set value to propertyDictionary?





Aucun commentaire:

Enregistrer un commentaire