当我尝试使用此接受的答案将列动态添加到我的数据表时,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
不会归还它们。这应该按预期工作:
public class TestObject
{
public string PorpertyOne => "First property";
public string PorpertyTwo => "Second property";
public string PorpertyThree => "Third property";
}