lundi 12 octobre 2020

C# Reflection Get List of Object

I have a problem fetching object from the array object that I made. It seems it didn't fetch the object see my code below:

Product Model

public class Product
{
    public string Id { get; set; }
    public List<ExcelName> ShortDesc { get; set; } // I want to get the object from here
}

Short Description Model

// get this object and the properties inside it.
public class ExcelName
{
    public string Name { get; set; }
    public string Language { get; set; }
}

My Code

private static T SetValue<T>(Dictionary<string, object> objectValues)
{
    var type = typeof(T);
    var objInstance = Activator.CreateInstance(type);
    if (!type.IsClass) return default;
    foreach (var value in objectValues)
    {
         if (value.Key.Contains(":Language="))
         {
             var propName = value.Key.Split(':')[0];
             // propName is ShortDesc object
             var propInfo = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(e => e.Name.ToLower() == propName.ToLower().Replace(" ", ""));
             if (propInfo == null) continue;
             if (propInfo.PropertyType.IsGenericType)
             {
                 // I want to get the type and properties from T generic using reflection instead static
                 var name = typeof(ExcelName);
                 var excelNameObjectInstance = Activator.CreateInstance(name);
                 foreach (var propertyInfo in name.GetProperties())
                 {
                     propertyInfo.SetValue(excelNameObjectInstance, value.Value, null);
                 }

                 // add excelNameObjectInstance object to the list in ShortDesc
              }
         }
    }

}

How to fetch the object from the list of ShortDesc to get the ExcelName objects.





Aucun commentaire:

Enregistrer un commentaire