2016-11-15 15 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來實現此目的。如何使用列表

+7

覆蓋'ToString'。 –

+5

重寫'a'中的'ToString()' – Ric

+0

如何做到這一點? – ABM

回答

2

您可以覆蓋中的ToString()A

public class A 
{ 
    public int a = 100; 

    public override string ToString() 
    { 
     return a.ToString(); 
    } 
} 
0

如果你不想使用.athis然後爲了這個目的,你可以使用反射:

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)); 
} 

注:
我我不確定你的最終目標是什麼,但我幾乎可以肯定有很多更簡單的方法可以做到這一點。

+0

不,我想通過使用ArrayList來實現此解決方案 – ABM

+0

只需在您的原始foreach中複製我的代碼即可。它仍然會使用你的ArrayList。 –

+0

我想在列表中添加該值,就像我在代碼中看到的那樣,我試圖添加到列表中 – ABM

0

我想這可能是你問的:

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(); 
     } 
    } 
}