C# 为每个对象动态添加列到 DataTable 属性
C# Dynamically add columns to DataTable for each Object Property
当我尝试使用 this accepted answer 将列动态添加到我的 DataTable 时,if
条件永远不会为真。我试过将 struct
更改为 class
,并且尝试过在 GetProperties
上使用和不使用 BindingFlags
。我错过了什么?
public partial class mainForm : Form
{
public DataTable DeviceDataTable;
public mainForm()
{
InitializeComponent();
AttachToTable(new TestObject());
}
public void AttachToTable(params object[] data)
{
for (int i = 0; i < data.Length; i++)
{
if (data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Length > DeviceDataTable.Columns.Count)
foreach (PropertyInfo info in data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
DeviceDataTable.Columns.Add(info.Name, data[i].GetType());
}
}
DeviceDataTable.Rows.Add(data);
}
public struct TestObject
{
public static readonly string Porperty_One = "First property";
public static readonly string Porperty_Two = "Second property";
public static readonly string Porperty_Three = "Third property";
}
}
您的示例结构很糟糕,因为它没有属性,甚至没有实例,只有静态字段。所以 Type.GetProperties
不会 return 他们。这应该按预期工作:
public class TestObject
{
public string PorpertyOne => "First property";
public string PorpertyTwo => "Second property";
public string PorpertyThree => "Third property";
}
当我尝试使用 this accepted answer 将列动态添加到我的 DataTable 时,if
条件永远不会为真。我试过将 struct
更改为 class
,并且尝试过在 GetProperties
上使用和不使用 BindingFlags
。我错过了什么?
public partial class mainForm : Form
{
public DataTable DeviceDataTable;
public mainForm()
{
InitializeComponent();
AttachToTable(new TestObject());
}
public void AttachToTable(params object[] data)
{
for (int i = 0; i < data.Length; i++)
{
if (data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Length > DeviceDataTable.Columns.Count)
foreach (PropertyInfo info in data[i].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
DeviceDataTable.Columns.Add(info.Name, data[i].GetType());
}
}
DeviceDataTable.Rows.Add(data);
}
public struct TestObject
{
public static readonly string Porperty_One = "First property";
public static readonly string Porperty_Two = "Second property";
public static readonly string Porperty_Three = "Third property";
}
}
您的示例结构很糟糕,因为它没有属性,甚至没有实例,只有静态字段。所以 Type.GetProperties
不会 return 他们。这应该按预期工作:
public class TestObject
{
public string PorpertyOne => "First property";
public string PorpertyTwo => "Second property";
public string PorpertyThree => "Third property";
}