2016-11-15 1 views
0
namespace ConsoleApplication3 
{ 
    class A 
    { 
     public int a = 100; 
    } 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ArrayList list = new ArrayList(); 
      A a = new A() ; 
      list.Add(a); 
      foreach (var i in list) 
      { 
       Console.WriteLine(i); 
      } 
      Console.ReadKey(); 

     } 
    } 
} 

를 사용하여 클래스에서 데이터를 전달하는 방법? 나는 이것을 ArrayList을 사용하여 계속하고 싶습니다. 이 목적을 위해 다음 .athis를 사용하지 않을 경우어떻게 목록이 코드는 출력을 제공

+7

재정의'ToString'을 :

public class A { public int a = 100; public override string ToString() { return a.ToString(); } } 

+5

'a '에서 ToString()을 오버라이드 – Ric

+0

하는 방법? – ABM

답변

2

A 클래스에서 ToString()을 무시할 수 있습니다.

using System; 
using System.Collections; 

namespace ConsoleApplication3 
{ 
    class A 
    { 
     public int a = 100; 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      var list = new ArrayList(); 
      A a = new A(); 
      list.Add((int)typeof(A).GetField("a").GetValue(a)); 
      foreach (var i in list) 
      { 
       Console.WriteLine(i); 
      } 

      Console.ReadKey(); 
     } 
    } 
} 
0

, 당신이 사용할 수있는 반사 :

using System.Reflection; 
... 

및 Foreach 루프 당신의 :

FieldInfo[] fields = i.GetType().GetFields(); // All fields of the class A will be here. 
foreach (var field in fields) 
{ 
    // write out them all 
    Console.WriteLine(field.GetValue(i)); 
} 

참고 :
I 당신의 최종 목표는 무엇인지 모르겠지만, 그 일을하는 더 쉬운 방법이 거의 있다고 확신합니다.

+0

아니오 ArrayList를 사용하여이 솔루션을 얻고 싶습니다. – ABM

+0

원본 코드에서 코드를 복사하십시오. 여전히 ArrayList를 사용합니다. –

+0

내 코드에서 볼 수있는 것처럼 목록에 해당 값을 추가하려고합니다. 목록에 추가하려고했습니다. – ABM

0

나는이 당신을 위해 무엇을 요구 할 수있다 생각합니다.
관련 문제