.net 向ItemControl添加元素的成本有多高?
我只是有一个一般的.NET查询: 假设我有一个大的(内存大小)类 如果我向ItemControl(如ListBox或Datagrid)添加一个项,如下所示.net 向ItemControl添加元素的成本有多高?,.net,.net-3.5,.net,.net 3.5,我只是有一个一般的.NET查询: 假设我有一个大的(内存大小)类 如果我向ItemControl(如ListBox或Datagrid)添加一个项,如下所示 BigClass b = new BigClass(); ListBox1.Items.Add(b); 这样做的资源使用情况如何?添加的项是引用的还是实例的副本(导致大量内存使用) 谢谢。它将作为参考添加。.NET对象没有隐式复制语义。为了确保这一点,我刚刚做了一个快速而肮脏的测试,ListBox1。Items不复制,而是保留一个引用 以下
BigClass b = new BigClass();
ListBox1.Items.Add(b);
这样做的资源使用情况如何?添加的项是引用的还是实例的副本(导致大量内存使用)
谢谢。它将作为参考添加。.NET对象没有隐式复制语义。为了确保这一点,我刚刚做了一个快速而肮脏的测试,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
}
}
}
谢谢,这确实很有帮助。你是对的,但这并不意味着ListBox.Items的“add”方法中没有克隆
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
}
}
}