简体   繁体   English

c#list。添加并发症

[英]c# list.Add complication

I have class MyClass() in which I am calling method from another SecondClass() it is done is foreach loop. 我有类MyClass(),我从另一个SecondClass()调用方法它是foreach循环。 In this method I have a list to which I am putting some data. 在这个方法中,我有一个列表,我将一些数据。 But everytime this method is called my list is filled from the begining. 但每次调用此方法时,我的列表都会从开头填充。 I lose all previously inserted data. 我丢失了以前插入的所有数据。 How can I fix this problem? 我该如何解决这个问题?

foreach(string items in description)
{
    SecondClass method = new SecondClass();
    method.DoThis(items);
}

MyClass() with this method looks something like this 使用此方法的MyClass()看起来像这样

public void DoThis(string items)
{
    List<MyClass> list2 = new List<MyClass>();
    if(//somethis)
    {
         /// some more code
         list2.Add(sk);
    }
}

I edited the code, I had some mistakes. 我编辑了代码,我犯了一些错误。 Sorry 抱歉

You're initializing list2 inside DoThis 's scope. 你正在DoThis的范围内初始化list2 You have to declare it as a member of MyClass , like the following: 您必须将其声明为MyClass的成员,如下所示:

class MyClass
{
      //if MyClass is sealed or static, then change protected to private.
      //if you need to access it from outside MyClass, change it to public.
      protected List<SrodkowaKolumna> list2 = new List<SrodkowaKolumna>();

      public void DoThis(string items)
      {
           if(//somethis)
           {
                 /// some more code
                 list2.Add(sk);
           }
      }
 }

Try this code: 试试这段代码:

It should store your list as field in class. 它应该将您的列表存储为类中的字段。 When you were initializing list2 in DoThis, every single call was making new empty list2. 当你在DoThis中初始化list2时,每个调用都会创建一个新的空list2。

public class MyClass
{
    List<SrodkowaKolumna> list2;
    public MyClass()
    {
         list2 = new List<SrodkowaKolumna>();
    }
    //.... other code

    public void DoThis(string items)
    {  
       for(//somethis)
       {
         /// some more code
                list2.Add(sk);
       }
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM