0
我对这个程序的输出有点困惑。这是代码中的一个真实场景,但我已将其缩短为以下内容:为什么这个程序的输出不是我认为的
class Program
{
static void Main(string[] args)
{
Dummy obj = new Dummy();
obj.FillList();
obj.MyPublicMethod();
}
}
public class Dummy
{
public Dummy()
{
NamesCollection = new List<string>();
}
public ICollection<string> NamesCollection { get; set; }
private List<string> _names;
public List<string> Names
{
get
{
//return _names ??
// (_names = NamesCollection.ToList());
if (ReferenceEquals(_names, null))
{
_names = NamesCollection.ToList();
}
if (_names.Count != NamesCollection.Count)
{
_names.Clear();
_names.Add("Aamir");
}
return _names;
}
set { _names = value; }
}
public void FillList()
{
this.NamesCollection.Add("Atif");
this.NamesCollection.Add("Ali");
this.NamesCollection.Add("haris");
this.Names.Add("Asif");
}
public void MyPublicMethod()
{
foreach (var item in Names)
{
Console.WriteLine(item);
}
//I am thinking that output should be:
//Atif
//Ali
//haris
//Aamir
//But the output that I am getting is only:
//Aamir
}
}
我认为清理发生在foreach循环发生时。你说这发生在this.Names.Add(“Asif”)时。但是当添加发生时,get方法在添加之前发生。 _names.Count = NamesCollection.Count = 3。 –