只是偶然发现了这个旧职位,并想加我两美分。通常,如果我有疑问,我会在任何对象上快速使用GetHashCode()方法来检查身份。所以对于以上-
public class MyObject
{
public int SimpleInt { get; set; }
}
class Program
{
public static void RunChangeList()
{
var objs = new List<MyObject>() { new MyObject() { SimpleInt = 0 } };
Console.WriteLine("objs: {0}", objs.GetHashCode());
Console.WriteLine("objs[0]: {0}", objs[0].GetHashCode());
var whatInt = ChangeToList(objs);
Console.WriteLine("whatInt: {0}", whatInt.GetHashCode());
}
public static int ChangeToList(List<MyObject> objects)
{
Console.WriteLine("objects: {0}", objects.GetHashCode());
Console.WriteLine("objects[0]: {0}", objects[0].GetHashCode());
var objectList = objects.ToList();
Console.WriteLine("objectList: {0}", objectList.GetHashCode());
Console.WriteLine("objectList[0]: {0}", objectList[0].GetHashCode());
objectList[0].SimpleInt = 5;
return objects[0].SimpleInt;
}
private static void Main(string[] args)
{
RunChangeList();
Console.ReadLine();
}
在我的机器上回答-
- 对象:45653674
- objs [0]:41149443
- 对象:45653674
- 对象[0]:41149443
- objectList:39785641
- objectList [0]:41149443
- whatInt:5
因此,列表所携带的对象本质上在上述代码中保持不变。希望该方法有所帮助。
.ToList()
制作浅表副本。引用被复制,但是新引用仍然指向与原始引用相同的实例。当你想到它,ToList
不能创造任何new MyObject()
时候MyObject
是一个class
类型。