2016-10-12 2 views
-6

객체의 배열을 가지고 있는데, 어떻게 그 객체를 콘솔에 출력 할 수 있습니까?콘솔에 객체 배열을 출력하십시오.

속성과 값을 인쇄해야합니다.

object[] attrs; 
attrs = prop.GetCustomAttributes(true); 

나는 리플렉션을 사용해야하지만 어떻게 사용해야하는지 잘 모릅니다.

+0

그래서 지금까지 밝혀진 연구는 무엇입니까? 질문에 대답하는 것이 왜 도움이되지 않습니까? –

+0

'foreach (attrs에있는 var 항목) ....... ' –

+0

내 생각을 이해하지 못했고, 속성 이름과 해당 값을 인쇄해야한다고 생각합니다. –

답변

0

리플렉션을 사용해야합니다. 다음은 샘플입니다.

static void Main(string[] args) 
    { 
     string obj1 = "a string"; 
     int obj2 = 12; 
     DateTime obj3 = DateTime.Today; 

     object[] obj_array = { obj1, obj2, obj3 }; 

     foreach (object obj in obj_array) 
     { 
      //Print value 
      Console.WriteLine("Value: " + obj.ToString()); 

      //Print property names 
      Console.WriteLine("Property Names:"); 
      foreach (PropertyInfo prop in obj.GetType().GetProperties()) 
      { 
       Console.WriteLine(prop.Name); 
      } 
      Console.WriteLine(); 
     } 
     Console.Read(); 
    } 

EDIT : 죄송합니다. 아마도 객체 자체의 속성 값을 가져오고 싶었을 것입니다. 이 경우 다른 샘플이 있습니다.

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyObject myobj = new MyObject("prop1", "prop2"); 
     object[] obj_array = { myobj }; 

     foreach (object obj in obj_array) 
     { 
      foreach (PropertyInfo property in obj.GetType().GetProperties()) 
      { 
       Console.WriteLine("Property Name: " + property.Name); 
       Console.WriteLine("Property Value: " + property.GetValue(obj)); 
      } 
     } 
     Console.Read(); 
    } 
} 
public class MyObject 
{ 
    public string Property1 { get; set; } 
    public string Property2 { get; set; } 
    public MyObject(string p1, string p2) 
    { 
     Property1 = p1; 
     Property2 = p2; 
    } 
} 
0

시도해 볼 수 있습니다. Console.WriteLine(string.Join(",", attrs));

+0

인데, 객체의 배열인데, 마녀는 속성과 그 값을 포함하고 있습니다. 그리고 그것을 인쇄 할 필요가 있습니다. –

관련 문제