分配后意外清除列表 [英] Lists getting cleared unexpectedly after assignment

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

问题描述

  Class ListHolder{公共列表< char>列表;公共ListHolder(List char l){this.List = l;}}班级计划{静态void Main(string [] args){List< char>a =新的List< char>();a.添加('s');ListHolder c =新的ListHolder(a);明确();Console.WriteLine(c.List.Count);}} 

我已经在该类中添加了一些列表,然后清除了该列表并在该类中写入了列表的计数...我希望输出应该为"1"(因为该类中的列表包含字母"s"),但改写为"0".a.Clear怎么可能清除班级中的名单?如何只清除Main中的列表和class类中的列表?

解决方案

由于您传递的是引用而不是列表本身,因此清除列表后将获得0.

您要做的是将包含其他列表值的新 List 传递给类:

  cl c = new cl(new List< char>(a)); 

通过这种方式,即使您清除了主要"列表,在您的班级中,您也将有1个项目计数.

希望这会有所帮助.

class ListHolder
{
    public List<char> List;
    public ListHolder(List<char> l)
    {
        this.List = l;
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<char> a = new List<char>();
        a.Add('s');
        ListHolder c = new ListHolder(a);
        a.Clear();
        Console.WriteLine(c.List.Count);
    }
}

I've put some list into that class, than I cleared the list and wrote the count of the list in the class... I would expect that the output should be "1" (as the list in the class contains the letter 's') but instead it writes "0". How is possible, that a.Clear clears even the list in the class? How can I achieve clearing only the list in the Main and the list in the class letting be?

解决方案

Since you are passing a reference instead of the list itself, you will get 0 after clearing your list.

What you have to do is passing to the class a new List containing the other list's values:

cl c = new cl(new List<char>(a)); 

This way, even if you clear the 'main' list, in your class you'll have 1 as items count.

Hope this helps.

这篇关于分配后意外清除列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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