2011-12-12 83 views
1

你創建一個類,將代表2列行:如何訪問列表的公共和私有成員<CustomClass>

public class Foo 
{ 
    // obviously you find meaningful names of the 2 properties 

    public string Column1 { get; set; } 
    public string Column2 { get; set; } 
} 

,然後你在List<Foo>存儲:

List<Foo> _items = new List<Foo>(); 
_items.Add(new Foo { Column1 = "bar", Column2 = "baz" }); 

哪有我將列表框的數據源設置爲項目?如果我做

ListBox1.DataSource = _items; 

我會看到在列表框,而不是它包含

回答

4

訪問公共成員文本list of Objects,你只需通過項目迭代:

foreach(Foo item in _items) 
{ 
    // use item 
} 

由於您的收藏是List<T>,您還可以通過索引來訪問的項目:

string col1 = _items[0].Column1; // First item in list's column1 

但是,您不能訪問Foo私人成員。將Foo專用成員的全部要點是阻止Foo課程以外的訪問。

0

您正在尋找_items[42]和/或foreach循環。

1

覆蓋Foo類中的ToString()方法。列表框使用它來轉換對象爲字符串

樣品:

class A 

{ 

    public int I 

    { 

     get; 

     set; 

    } 

    public override string ToString() 

    { 

     return "I=" + I.ToString(); 

    } 

} 



public partial class Form1 : Form 

{ 

    public Form1() 

    { 

     InitializeComponent(); 

    } 



    private void Form1_Load(object sender, EventArgs e) 

    { 

     listBox1.DataSource = new[] 

     { 

      new A { I = 1}, 

      new A { I = 2}, 

     }; 

    } 

} 
+0

在理論上聽起來不錯,但我可能失去了一些東西。你能發佈你的代碼嗎? –

+0

當然:http://pastebin.com/mqb0QdGi – Novakov

+0

該網站在工作時被阻止。你能複製並粘貼到你的答案嗎? –