Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 副本与参考书_C# - Fatal编程技术网

C# 副本与参考书

C# 副本与参考书,c#,C#,为什么此代码导致Shipping.Items.Count和CombinedShipping.Items.Count都等于零 private static InboundShipment CombineLikeIsbns(InboundShipment shipment) { // shipment.Items has a count of 3 var distinctIsbns = shipment.Items.Select(i => i.ISBN).Distinct()

为什么此代码导致Shipping.Items.Count和CombinedShipping.Items.Count都等于零

private static InboundShipment CombineLikeIsbns(InboundShipment shipment)
{
    // shipment.Items has a count of 3

    var distinctIsbns = shipment.Items.Select(i => i.ISBN).Distinct().ToList();

    var combinedShipment = shipment;
    combinedShipment.Items = new List<InboundShipmentItem>();

    // Now both combinedShipment and shipment have an empty List in the .Items property

    ...

    return combinedShipment;
}
私有静态InboundShipping组合ElikesBNs(InboundShipping)
{
//装运。项目数为3
var differentisbns=shipping.Items.Select(i=>i.ISBN.Distinct().ToList();
var组合装运=装运;
CombinedShipping.Items=新列表();
//现在,CombinedShipping和Shipping在.Items属性中都有一个空列表
...
退货合并装运;
}
[编辑] 当我将CombinedShipping.Items设置为相同时,如何避免将Shipping.Items设置为新列表?

此语句:

var combinedShipment = shipment;
装运
的值复制到
组合装运
中。假设
inboundshipping
是一个类,
shipping
的值是一个引用,而不是对象本身

现在我们有两个变量,它们都指向同一个对象。使用哪个变量对对象进行更改并不重要——更改将通过两个变量可见

如果要创建原始对象的新“副本”,则必须显式地这样做。很难确切知道您在这里需要做什么,因为您没有向我们提供有关
inboundshipping
类型的详细信息

有关更多详细信息,请参阅我的。请注意,这是C#和.NET的一个重要部分,在进一步研究之前,您应该对它充满信心—在掌握了基本知识之前,诸如LINQ(及其lambda表达式、延迟执行等)之类的高级主题将很难理解。

var combinedShipment = shipment; 

将CombinedShipping引用设置为指向与装运相同的实例。因此,当您清除CombinedShipping上的项目时,它会清除该单个实例的项目。

分配
var CombinedShipping=shipping导致
组合装运
装运
引用完全相同的对象。这有点像在同一个纸板箱上贴两个不同的标签

因此,从标有
CombinedShipping
的框中取出所有项目的下一行也会导致标有
Shipping
的框清空。因为它们是同一个盒子,有两个不同的标签

如果您想创建一个包含不同项目的新装运对象,您需要从创建一个新装运对象开始

var combinedShipment = new InboundShipment();

实际的代码可能不能完全像那样。假设您希望组合装运
的某些属性与装运的属性相同,则必须手动确保发生这种情况。根据
inboundshipping
的设计方式,这将需要将所需的值传递到构造函数中,通过属性设置所需的值,或者两者的混合。

我们需要有关
inboundshipping
type.Yep的信息。我很尴尬。谢谢你,乔恩。