通用列表问题 [英] Generic Lists question

查看:58
本文介绍了通用列表问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我在使用C#时遇到了一些问题

我宁愿用一小段代码来说明我的观点:

Hello everyone, I am having a little problem with C#

I''d rather illustrate my point with a little piece of code:

List<int> List1, List2;
List1 = new List<int>();

List1.AddRange(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });
List2 = List1;

List2.Reverse();



在上面的代码中,在List2为.Reversed()之后,List1的项目
还颠倒了!

我猜是



In the above code, after List2 is .Reversed(), the items of List1
are ALSO reversed!

I am guessing that

List2 = List1


模仿普通C语言中的指针之类的内容,
即List2指向List1(通过引用),但是
我以为使用此命令可以启动List2,
并基本上将列表1"复制到列表2",其中列表2"为
独立实体.

这是正常现象还是我在这里错过了一些东西?
另外,您建议采用哪种方法来实现自己的目标
在这里找?

目前我正在使用


mimics something like pointers in plain C,
ie List2 points to List1 (by reference), but
I thought that using this command I would initiate List2,
and basically "copy" List1 to List2, with List2 being an
independent entity.

Is this behaviour normal or am I missing something here?
Also, which approach do you propose to achieve what I am
looking for here?

Currently I am using

List2.AddRange(List1)


而不是上面的声明,这似乎是


instead of the above statement, which seems
to take care of the "dependency" issue

推荐答案

这很正常.
声明列表时:
This is normal.
When you declare a list:
List<int> int1;

,您正在声明一个引用List< int>的变量.不是包含整数的实际对象-正如您所说的,很像普通c语言中的指针.
因此,当您声明两个列表时:

you are declaring a variable that references a List<int> not the actual object that hold the integers - as you say, much like a pointer in plain c.
So when you declare two lists:

List<int> list1 = new List<int>();
List<int> list2 = list1;

您将获得两个指向同一对象的引用.
如果您在C:
中做到了

You get two references which point at the same object.
If you did it in C:

int* p1 = (int*) malloc(1000);
int *p2 = p1;
*p1 = 42;

您会期望* p1和* p2包含42.

基本上,将您在C#中声明的任何变量都视为引用-它不是真的,还有值类型-而且您不会做错太多.

You would expect *p1 and *p2 to contain 42.

Basically, think of any variable you declare in C# as a reference - it''s not true, there are value types as well - and you won''t go too far wrong.


在此代码中,这些列表变量是引用,因为通用类System.Collections.Generic.List是类,因此是引用类型.

引用类似于指针,但有很大的不同.它们是托管CLR世界中的指针.在运行期间可以更改对象的物理位置.如果要依靠对象的固定位置,则需要使用unsafe代码固定"它们.有时,它用于加速数组的工作,与非托管代码的协作等.

—SA
In this code, those list variable are references, because the generic class System.Collections.Generic.List is class and hence a reference type.

References are analogous to pointers, but very different. They are the pointers in managed CLR world. The physical locations of the objects can be changed during run time. If you want to rely in fixed positions of object, you need to "pin" them using unsafe code. Sometime it''s used for acceleration of work with the arrays, collaboration with unmanaged code and the like.

—SA


这篇关于通用列表问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆