2017-01-24 3 views
0

this accepted answer을 사용하여 동적으로 DataTable에 열을 추가하려고하면 if 조건이 true가 아닙니다. structclass으로 변경하려고 시도했으며 GetPropertiesBindingFlags과 함께 시도했으나 시도하지 않았습니다. 내가 뭘 놓치고 있니?C# 각 개체 속성에 대해 DataTable에 동적으로 열을 추가합니다.

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"; 
    } 
} 
+0

인스턴스 구조체는 속성이 없으며 인스턴스 필드도 정적 필드 만 있기 때문에 잘못되었습니다. 그래서 당신의 Type.GetProperties 그들을 반환하지 않습니다. –

+0

@TimSchmelter 맞습니다! 'get; set;을 TestObject 프라퍼티에 적용하고'static readonly'를 제거하면 문제가 해결된다. 'GetProperties()'가'static readonly' 문자열을 반환하지 않는다는 것을 몰랐습니다. 당신이 당신의 대답을 정교하게한다면 나는 그것을 인정받은 사람으로 표시 할 것입니다. – user5825579

답변

0

예제 구조체에는 속성이 없으므로 인스턴스가 아니라 정적 필드 만 있기 때문에 잘못되었습니다. 따라서 Type.GetProperties은 반환하지 않습니다.

public class TestObject 
{ 
    public string PorpertyOne => "First property"; 
    public string PorpertyTwo => "Second property"; 
    public string PorpertyThree => "Third property"; 
} 
관련 문제