关于List< t>的问题 [英] question about List<t>

查看:51
本文介绍了关于List< t>的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Visual Studio 2017,并且正在编写WPF程序.  

I am using Visual Studio 2017, and I am writing a WPF program.  

(为便于理解,我将Cards和CurrentCard显示为在本地声明,但实际上是在方法外部声明的.)

(for ease of understanding, I am showing Cards and CurrentCard as declared locally, but it is actually declared outside the method.)

我有这个代码.

List<Card> Cards = new List<Card>();

Card CurrentCard = new Card();

Card CurrentCard = new Card();

...将信息添加到Card.

... add info to Card.

Cards.Add (CurrentCard); CurrentCard = null;

Cards.Add( CurrentCard ); CurrentCard = null;


最后一行代码对卡集合中的第一个也是唯一条目没有影响,尽管CurrentCard的值设置为null,但Cards [0]中的值保留了其信息.

The last line of code has no affect on the first and only entry in the collection of cards and though the value CurrentCard is set to null, the value in Cards[0] retains its information.

但是,如果我以不太生动的方式更改CurrentCard变量,则在List中对其进行更改.  

However, if I were to alter the variable CurrentCard in a less dramatic way, then it is changed in the List.  

我的问题是,为什么Cards [0]不会设置为null.

My question is, why doesn't Cards[0] get set to null. 

将CardId设置为12的行确实更改了Cards [0]中的值.

The line that sets the CardId to 12, does change the value in Cards[0].

List<Card> Cards = new List<Card>();

Card CurrentCard = new Card();

... add info to Card.

 Cards.Add( CurrentCard );         
 CurrentCard.CardId = 12

对此我感到困惑,如果有人可以解释为什么这样做,我将不胜感激.  与我认为的工作方式不符.

I am confused on this and if someone could explain why it works this way, I would appreciate it.  It doesnt match how I thought things work.

推荐答案

CurrentCard 是一个指向类型为实例化的对象的指针 . Cards.Add(CurrentCard); 行不是在添加对象,而是将实例化对象的另一个指针添加到 列表.这就是为什么将 CurrentCard 设置为null时,它不会更改存储在指针中的指针的原因. 列表.它所做的就是改变指针指向的位置.

CurrentCard is a pointer that points to an instantiated object of type Card.  The line Cards.Add (CurrentCard ); isn't adding the object but another pointer of the instantiated object to the List.  This is why when you set CurrentCard to null it doesn't change the pointer that was stored in the List.  All it's doing is changing where the pointer is pointing.

类似地, CurrentCard.CardId = 12; 更改的值 卡[0] ,因为两个指针都指向同一个实例化对象.

Similarly, CurrentCard.CardId = 12; changes the value of Cards[0] because both pointers are pointing to the same instantiated object.


这篇关于关于List&lt; t&gt;的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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