这可能是一个基本问题,但任何人都可以解释它是如何工作的。下面的代码仅仅是一个例子,但实时的情况可能发生在不同的地方。例如:在创建具有Orders属性的Customer之类的复杂对象时使用DTO。 Orders(= List)是否需要在Customer的构造函数中实例化,或者直接将其分配给查询结果或存储过程。将它分配给新列表对象和复制列表之间的区别
List<string> list1 = new List<string>()
{
"One", "Two","Three"
};
List<string> list2 = new List<string>();
list2 = list1;
foreach (var s in list2)
Console.WriteLine(s);
List<string> list3 = list1;
if (list3 != null) //is this the only difference
{
foreach (var s in list3)
Console.WriteLine(s);
}
我试着检查IL代码,但它不是自我解释。
IL_0031: stloc.0
IL_0032: newobj instance void class [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
IL_0037: stloc.1
IL_0038: ldloc.0
IL_0039: stloc.1
IL_003a: ldloc.0
IL_003b: stloc.2
IL_003c: nop
IL_003d: ldloc.1
IL_003e: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> class [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
IL_0043: stloc.s CS$5$0000
我张贴混乱的例子遗憾。下面是实际 场景
DTO:
在DAL层public class CustomerBO
{
public CustomerBO()
{
Orders = new List<OrderBO>();
}
List<OrderBO>() Orders { get; set;}
//other properties of customer
}
现在:
objCustomer.Orders = Repository.GetAll<OrderBO>("dbo.GetOrdersList");
我的问题是,这将是确定的,如果我初始化订单对象在CustomerBO构造(或者)跳过它并在表示层中检查null。
我很努力地在这里看到问题。你可以尝试更具体吗? –
list2是浪费的(除非优化器将其移除),因为您在堆上分配了一个新项目,然后忽略它并将该变量分配给以前的内存地址。 –
感谢您的回复。欣赏它。 – Sunny