为什么这个程序的输出不是我想的

时间:2014-03-05 06:50:48

标签: c# c#-4.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
    }
}

1 个答案:

答案 0 :(得分:3)

问题在于我的公共方法方法。当您执行foreach (var item in Names){}时,Names的get方法会执行。 _names.Count = 4,但NamesCollection.Count = 3。所以_names被清除。并添加'Aamir'。