c# - PropertyInfo set value List<object>

微笑、不失礼 提交于 2020-03-26 05:20:07

问题


PropertyInfo set value List<object>

show error in convert list <object>

I tried to convert to json and I couldn't

public class PurchaseBill
{
    public DateTime Date { get; set; }
    public string Type { get; set; }
    public string BillType { get; set; }
    public List<PurchaseProduct> Listproduct { get; set; }
}
public class PurchaseProduct
{
    public Int64 id { get; set; }
    public String itemId { get; set; }
    public String image { get; set; }

}

code convert MySqlDataReader to list

public static List<T> DataReaderMapToList<T>(MySqlDataReader dr)
{
    List<T> list = new List<T>();
    T obj = default(T);
    while (dr.Read())
    {
        obj = Activator.CreateInstance<T>();


        foreach (PropertyInfo prop in obj.GetType().GetProperties())
        {
            if (!object.Equals(dr[prop.Name], DBNull.Value))
            {
                if (prop.PropertyType.Name == "List`1")
                {
                    var getval = Convert.ChangeType(dr[prop.Name], typeof(string)).ToString();

                    var objectType = prop.PropertyType.GetGenericArguments().First();

                    var Object = Activator.CreateInstance(objectType);
                    var company = JsonConvert.DeserializeObject<List<object>>(getval);

                    // error in next line 'can`t convert to list`1 '
                    prop.SetValue(obj, Convert.ChangeType(dr[prop.Name], prop.PropertyType), null);
                }
                else
                {
                    prop.SetValue(obj, Convert.ChangeType(dr[prop.Name], prop.PropertyType), null);
                }
            }
        }
       list.Add(obj);

    }
    return list;
}

mysql MySqlCommand cmd = new MySqlCommand(query, connection); //Create a data reader and Execute the command MySqlDataReader dataReader = cmd.ExecuteReader(); //Read the data and store them in the list list = DataReaderMapToList<T>(dataReader);

show error in convert list

show error debug An exception of type 'System.InvalidCastException' occurred in mscorlib.dll but was not handled in user code Additional information: Invalid cast from 'System.String' to 'System.Collections.Generic.List`1[[test.Purchase_Management+PurchaseProduct, App, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. 

please i want solution

来源:https://stackoverflow.com/questions/57963744/c-sharp-propertyinfo-set-value-listobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!