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

本文关键字:返回 数组 GetProperties 类型 DataTable-- FileHelpers | 更新日期: 2023-09-27 18:17:00

我已经成功地将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.
}

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

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;
    }

问题出在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;
    }

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

Employee类包含字段,而不是属性。使用

myType.GetFields()

使用Properties时:您需要指定GetProperties的作用域,尝试返回所有属性类型:GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

当使用字段(即没有获取/设置(时,它是相似的,只是不同的函数。请参阅:http://msdn.microsoft.com/en-us/library/ch9714z3.aspx

在这个类片段中没有任何属性。我将此代码用于web服务中的Reference.cs类。

Employee objE = new Employee();
var members = objE.GetType().GetFields().Select(m => new
{
    Name = m.Name,
    MemType = m.MemberType,
    RtField = m.GetType(),
    Type = m.FieldType,
    MemAtt = m.GetCustomAttributes(true)
});