【问题标题】:Why is PropertyInfo[] not populating?为什么 PropertyInfo[] 没有填充?
【发布时间】:2020-04-28 12:42:57
【问题描述】:

我目前正在将 WebForms 应用程序重建为 MVC。这种转换的一部分需要将 DataSets 和 DataTables 映射到对象中。我用来完成此操作的方法是:

    public static List<T> DataTableToEntityList<T>(DataTable sourceDataTable, params PropertyMapper[] propertyMappings) where T : class, new()
    {
        List<T> entityList = new List<T>();

        if (sourceDataTable != null)
        {
            // Get all properties of the Type T
            PropertyInfo[] entityProperties = typeof(T).GetProperties();

            foreach (DataRow dr in sourceDataTable.Rows)
            {
                // Create Instance of the Type T
                T entity = new T();
                PopulateEntityClass<T>(entity, dr, entityProperties, propertyMappings);
                entityList.Add(entity);
            }
        }

        return entityList;
    }

主程序是:

    public static void Main(string[] args)
    {
        Program program = new Program();
        DataTable dt = program.createData();

        List<superadminAction> list = Helper.DataMappingHelper.DataTableToEntityList<superadminAction>(dt, null);


        foreach(superadminAction action in list)
        {
            if (action.Title != null)
                Console.WriteLine(action.Title);
            else
                Console.WriteLine("null values");
        }
        Console.ReadLine();

    }

我要转换的对象是:

public class superadminAction
{
    public int SuperAdminActionCounter;
    public string Procedure, Title, Description, TemplateDescription; 
}

}

我不知道为什么我无法访问 Main(...) 函数中的属性。

任何想法都将不胜感激。

【问题讨论】:

  • 可能是因为你在superadminAction类中没有属性
  • 没有属性不会抛出异常;它会返回一个空数组。
  • @madreflection 我猜,这个异常发生在 PopulateEntityClass&lt;T&gt;(entity, dr, entityProperties, propertyMappings); 调用中的某个地方。 @urizark 你还为propertyMappings 传递了一个null
  • @PavelAnikhouski:也许吧,但这不是问题所说的。它指出typeof(T) 抛出异常,我们看到在调用PopulateEntityClass&lt;T&gt; 之前。
  • @madreflection 绝对,我现在就这样做。感谢您的帮助

标签: c# asp.net-mvc webforms dataset typeof


【解决方案1】:

Procedure、Title、Description 等是字段而不是属性。要获取它们,请使用 typeof(T).GetFields()。

【讨论】:

    猜你喜欢
    • 2017-01-18
    • 1970-01-01
    • 2015-04-28
    • 2011-12-28
    • 2017-01-21
    • 2014-10-03
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多