2009-04-11 18 views
1

我只是一個普通的.NET查詢:向ItemControl添加元素的代價是多大?

假設我有一個大的(內存大小)

public class BigClass 
{ 
... 
} 

如果我添加項目到ItemControl如列表框或數據網格這樣

BigClass b = new BigClass(); 
ListBox1.Items.Add(b); 

這樣做的資源使用情況如何?添加的項目被引用或是由實例構成的副本(導致大量內存使用)?

謝謝。

回答

3

它將被添加爲參考。 .NET對象沒有隱式複製語義。

+0

你是對的,但這並不意味着有一個在ListBox.Items – user88637 2009-04-11 23:18:24

0

可以肯定的是,我只是做了一個快速和骯髒的測試,ListBox1.Items不做一個副本,而是保留一個參考。

下面是完整的代碼:

public class A 
{ 

    int a; 

    public int A1 
    { 
     get { return a; } 
     set { a = value; } 
    } 

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

    private void Form1_Load(object sender, EventArgs e) 
    { 
     A a = new A(); 
     a.A1 = 4; 

     A b = new A(); 
     b.A1 = 4; 

     listBox1.Items.Add(a); 
     listBox1.Items.Add(b); 

     A c = listBox1.Items[0] as A; 
     A d = listBox1.Items[1] as A; 

     if(a.Equals(c)) 
     { 
      int k = 8; //program enter here so a is instance of c 
     } 

     if (a.Equals(d)) 
     { 
      int k = 8; //program doesn't enter here meaning a is not instance of d 
     } 


    } 
} 
+0

感謝的「添加」方法沒有克隆,這是非常有幫助的當然。 – Adam 2009-04-11 23:11:48