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

4

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

我需要基于该类创建一个 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;
    }

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

你的意思是什么?一个空数组吗? - stackErr
这意味着您没有任何公共属性。正如Dominic所提到的,您拥有字段而不是属性。 - stackErr
3个回答

18

您的Employee类包含字段,而不是属性。建议使用

myType.GetFields()

1
我甚至没有注意到那个。好眼力,Dominic。 - David C

5
当使用属性时: 您需要指定获取属性的作用域,尝试使用以下代码以返回所有属性类型:GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); 当使用字段(即无get/set)时,也是类似的,只需使用不同的函数。请参阅:http://msdn.microsoft.com/en-us/library/ch9714z3.aspx

你确定你要查找属性而不是字段吗?尝试使用GetFields。 - David C
再次感谢你,David。Dominic 几乎比你更快地提出了建议,所以我把答案归功于他,但我真的很感激你的帮助! - Nate
是的,他抓住了实际问题。祝你在所有的开发旅程中好运。 - David C

0

在这个类片段中,您没有任何属性。我使用此代码用于来自 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)
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接