PropertyInfo.SetValue在C#中设置值时抛出System.NullReferenceException

时间:2018-08-26 10:55:40

标签: c#

     public class Expenses
        {
            public Category Category { get; set; }
        }

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

所以我有这两节课。现在,我想将包含Expense类记录的DataTable转换为List。我正在使用这种方法:

public static List<T> ConvertDataTable<T>(DataTable dt)
    {
        List<T> data = new List<T>();
        foreach (DataRow row in dt.Rows)
        {

            T item = GetItem<T>(row);
            data.Add(item);
        }
        return data;
    }

    private static T GetItem<T>(DataRow dr)
    {
        try
        {
            Type temp = typeof(T);
            T obj = Activator.CreateInstance<T>();

            foreach (DataColumn column in dr.Table.Columns)
            {
                foreach (PropertyInfo pro in temp.GetProperties())
                {
                    if (pro.Name == column.ColumnName)
                    {
                        pro.SetValue(obj, dr[column.ColumnName], null);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            return obj;
        }
        catch (Exception)
        {

            throw;
        }
    }

Here are the records fetched from the database

As you can see the Category class object is null and I want to fill the values of CategoryName and CategoryID that are in Category class

以下是从数据库中获取的记录: 如您所见,Category类对象为null,我想填充Category类中的CategoryName和CategoryID的值。

那么如何实现呢?

1 个答案:

答案 0 :(得分:3)

您有两种选择:

1-删除Category属性,并将其Inherit移至Expenses类。

2-尝试以下方法:

    foreach (PropertyInfo pro in temp.GetProperties())
                    {
                        if(pro.PropertyType.IsClass && pro.PropertyType == typeof(Category))
                        {
                              Category subObj = Activator.CreateInstance<Category>();
                              foreach (PropertyInfo propertyin subObj.GetProperties())
                              {     
                                    if (dr[property.Name] != DBNull.Value) 
                                         property.SetValue(subObj , dr[property.Name], null);
                              }
                              pro.SetValue(obj, subObj , null);
                        }
                        if (pro.Name == column.ColumnName)
                        {
                             if (dr[pro.Name] != DBNull.Value) 
                                  pro.SetValue(obj, dr[column.ColumnName], null);
                        }
                        else
                        {
                            continue;
                        }
                    }

对于NullReferenceException,您必须检查如下值:

 if (dr[property.Name] != DBNull.Value) 

我希望它能帮上忙。