可能重复:
返回引用类型的方法会返回引用还是克隆副本?
我的一位同事说,当一个方法返回以下对象时,将创建一个新的实例/副本而不是返回引用:
public CustomerEntity Customer { get; set; }
public CustomerEntity GetCustomer() {
Customer = new CustomerEntity();
return Customer;
}
这是正确的吗?我的测试似乎表明情况不同,但我不确定如何确认。他担心将数据复制到新对象时的开销。
为了保险起见,在以下哪些方法/场景中会创建新对象?在哪些情况下调用类会访问对原始对象的引用或副本?假设'CustomerEntity'是一个非常大的对象。
public class CustMan {
public CustomerEntity GetCustomer() {
Customer = new CustomerEntity();
return Customer
}
public void FillCustomer(CustomerEntity customer)
{
customer = new CustomerEntity();
// Calling class:
// CustomerEntity ce = new CustomerEntity();
// l_custMan.FillCustomer(ce); WriteLine(ce.Name);
}
public void LoadCustomer()
{
Customer = new CustomerEntity();
// Calling Class access customerEntity via l_custMan.CustomerEntity
}
}
澄清:我的同事认为使用“Load”方法比使用“Get”方法更好。
l_custMan.Load();
CustomerEntity = l_custMan.Customer;
vs.
CustomerEntity = l_custMan.GetCustomer();