2014-01-23 3 views
0

저는 모든 클래스 속성을 가져 오기 위해 사전을 통해 루프를 만들려고합니다 (button_click의 코드가 수정하려고합니다). 대신 내 코드 모양처럼 지금 하나씩 그들을 작성하십시오. 현재 버전은 잘 작동하지만, 50 개 이상의 속성이 있어야한다면, 어떤 종류의 루프로 이것을 수행하는 더 쉬운 방법이 있어야한다고 생각합니다.사전을 반복하여 모든 클래스 속성을 가져 오는 방법은 무엇입니까?

class Person 
     { 
      public int PersNr { get; set; } 
      public string Name { get; set; } 
      public string BioPappa { get; set; } 
      public Adress Adress { get; set; } 


      public static Dictionary<int, Person> Metod() 
      { 
       var dict = new Dictionary<int, Person>(); 

       dict.Add(8706, new Person 
       { 
        Name = "Person", 
        PersNr = 8706, 
        BioPappa = "Dad", 
        Adress = new Adress 
        { 
         Land = "Land", 
         PostNr = 35343, 
         Stad = "city" 
        } 
       }); 

       dict.Add(840, new Person 
       { 
        Name = "Person", 
        PersNr = 840, 
        BioPappa = "Erik" 
       }); 
       return dict; 

      } 

     } 

public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      Dictionary<int, Person> myDic = Person.Metod(); 
      var person = myDic[int.Parse(textBoxSok.Text)]; 

      listBox1.Items.Add(person.Name); 
      listBox1.Items.Add(person.PersNr); 
      listBox1.Items.Add(person.BioPappa); 
      listBox1.Items.Add(person.Adress.Stad); 
      listBox1.Items.Add(person.Adress.PostNr); 
      listBox1.Items.Add(person.Adress.Land);   
     } 
    } 
+0

가 쉬울 것 루프를 가진 파일에서 사전을 채우기. 그래도 어딘가에 정의 된 모든 데이터가 필요합니다. –

+0

나에게 당신의 질문이 명확하지 않다 – akonsu

+0

그런 식으로, 그 easy.and 당신이 한 클래스에서 50 개의 속성을 가지고 있다면 디자인을 수정하십시오. –

답변

0

뭔가가 당신은 (System.Reflection를 사용하여) 시작하기 :

private void getProperties(Object obj, ListBox listBox1) 
{ 
    PropertyInfo[] pi = obj.GetType().GetProperties(); 
    foreach (PropertyInfo p in pi) 
    { 
     if (p.PropertyType.IsGenericType) 
     { 
      object o = p.GetValue(obj, null); 
      if (o != null) 
      { 
       if (o is Address) 
        getProperties(o, listBox1); 
       else 
        listBox1.Items.Add(o.ToString()); 
      } 
     } 
    } 
} 
+0

이 코드는 Person 클래스의 유형/속성 을 저장하는 배열을 생성합니까? 루프를 통해 단계를 밟을 때 반환되는 모든 null입니다. 또한 "using System.Reflection"을 사용해야합니까? 그렇지 않으면 오류가 발생합니다. – user3228992

+0

"if (p.PropertyType.IsGenericType)"을 "if (p.PropertyType.IsVisible)"로 변경합니다. 기본 클래스 마녀가 "사람"과 함께 작동하도록했습니다. :) 그러나 그것은 여전히 ​​내 Adress 클래스의 속성을 보여주지 않습니다. 왜 그런지 알아? – user3228992

+0

주소가 변경되었습니다. – klugerama

관련 문제