C#会改变返回的类对象改变原始状态吗?

时间:2016-10-03 13:23:22

标签: c# class

假设我有以下类结构:

public class spaList
{
    private List<customerItemFulfillment> customers;

    public customerItemFulfillment addNewCustomer(
      string customerNumber, string customerName)
    {
        customers.Add(new customerItemFulfillment(customerNumber, customerName));
        return customers[customers.Count - 1];
        //Would running .addItem() on this returned object affect the object in the list?
    }
}

public class customerItemFulfillment
{
    public string customerNumber { get; }
    public string customerName { get; }
    public List<itemFulfillment> fulfillmentItems { get; }

    public void addItem(string itemNumber, double rebateAmount, 
                         double fulfillmentPercent)
    {
        fulfillmentItems.Add(new itemFulfillment(itemNumber, 
                   rebateAmount, fulfillmentPercent));
    }

    public customerItemFulfillment(string customerNumber, string customerName)
    {
        this.customerNumber = customerNumber;
        this.customerName = customerName;
    }
}

如果我做了类似的事情:

spaList spaListings = new SpaList();
customerItemFulfillment newCustomer = spaListings.addNewCustomer(
                                   "customer name", "customer number");
newCustomer.addItem("item number", 25.00, 8.0);

这会改变customerItemFulfillment中的spaList.customers对象,还是只是该对象的副本?

即。我以后能够做一些像spaListings.customers[0].fulfillmentItems[0]那样的东西,并且那是我之前添加的项目吗?

1 个答案:

答案 0 :(得分:0)

对象是引用类型。这意味着从方法返回对象 reference ,而不是对象的副本。是的,您正在更改原始项目。如果这样做,最终可能会导致客户列表状态无效。

一种选择是返回对象的副本。最简单的方法是使用ICloneable的实现克隆类及其属性。