本文介绍了关于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.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;的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 05:45