FileHelpers中的DataTable类 - type.GetProperties()返回空数组

Nat*_*ate 4 .net c# filehelpers

我已成功将CSV文件拖到以下类中:

[DelimitedRecord(",")]
[IgnoreFirst(1)] // ignores first line of file, since it's a header
public class Employee {
    public string EmployeeId;
    public string FirstName;
    public string LastName;
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

我需要基于该类创建一个DataTable才能使用SqlBulkCopy.我找到了几个例子,但以下方法对我不起作用:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();

        foreach (PropertyInfo info in myType.GetProperties()) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }
Run Code Online (Sandbox Code Playgroud)

问题出在myType.GetProperties()上.它没有抛出错误,但它什么也没有返回.它应该返回的PropertyInfo数组是空的.已经有一段时间了,无法弄清楚问题......

编辑:我也使用这个变种没有成功:

private static DataTable createEmptyDataTable(Type myType) {
        DataTable dt = new DataTable();
        PropertyInfo[] infoArray = myType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        foreach (PropertyInfo info in infoArray) {
            dt.Columns.Add(new DataColumn(info.Name, info.PropertyType));
        }

        return dt;
    }
Run Code Online (Sandbox Code Playgroud)

Dom*_*nic 18

您的Employee类包含字段,而不是属性.请使用

myType.GetFields()
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 - 就是这样! (2认同)

Dav*_*d C 5

使用"属性"时:您需要指定"获取属性"的范围,尝试此操作以返回所有属性类型: GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

使用字段时(即没有get/set),它的相似,只是一个不同的功能.请参阅:http: //msdn.microsoft.com/en-us/library/ch9714z3.aspx