创建新元素将删除C#中列表中的第一个元素

时间:2016-03-18 10:03:19

标签: c# list

我创建了一个类-WhiteList - 包含从xml文件中读取的数据。我想列出这些元素,但是在第一个元素添加到列表后,我创建了一个新的数据元素,它删除了列表中第一个元素的争用。 I.E.似乎新的(元素)重新创建了对列表中元素的引用。

代码段:

namespace WhiteList
{
   public class WhiteListElement
   {
      private const byte EQL = 0;  
      private const byte CTN = 1;  
      private const byte COMMON_NAME = 0;  
      private const byte ORG = 1;  
      private const byte ORG_UNIT = 2;  
      private const byte LOC = 3;  
      private const byte STATE = 4; 
      private const byte COUNTRY = 5;   

      private static string[,] Subject;  
      private static string[,] Issuer;   

      private static string MinTlsLevel; 
      private static string Customer;


      public WhiteListElement()
      {
         Subject = new string[6, 2];
         Issuer = new string[6, 2];
         Customer = "";
         MinTlsLevel = "";
      }

      //---- set/get functions ---- example
      public string GetCommonName(bool SubjectVal, bool Name)
      {  
         if (true == SubjectVal) { if (true == Name) return Subject[COMMON_NAME, 0]; else return Subject[COMMON_NAME, 1]; }
         else { if (true == Name) return Issuer[COMMON_NAME, 0]; else return Issuer[COMMON_NAME, 1]; }
      }
      public void SetCommonName(bool SubjectVal, bool Name, string NewValue)
      {  
         if (true == SubjectVal) { if (true == Name) Subject[COMMON_NAME, 0] = NewValue; else Subject[COMMON_NAME, 1] = NewValue; }
         else { if (true == Name) Issuer[COMMON_NAME, 0] = NewValue; else Issuer[COMMON_NAME, 1] = NewValue; }
      }

   }
   class Program
   {
      public static void CreateWhiteList()
      {
         try
         {
            using (XmlReader reader = XmlReader.Create("WhiteList.xml"))
            {
               while (reader.Read())
               {
                  if (reader.NodeType == XmlNodeType.Element)
                  {
                     if (reader.Name == "Kunder")
                     {
                        while (reader.Read())
                        {
                           if (reader.NodeType == XmlNodeType.Element)
                           {
                              XElement el = (XElement)XNode.ReadFrom(reader);
                              if (el != null)
                              {
                                 WhiteListElement elem = new WhiteListElement();

                                 var noderef = el.FirstNode;
                                 elem.SetCustomer(el.Name.ToString());
                                 while (noderef.NextNode != null)
                                 {
                                    noderef = noderef.NextNode;
                                    string nodestring = noderef.ToString();
                                    if (nodestring[0] == '<')
                                    {
                                       int startindx, stopindx;
                                       string tag = nodestring.Substring(3);
                                       string data;
                                       tag = tag.Substring(0, tag.IndexOf('_'));
                                       startindx = nodestring.IndexOf('\"') + 1;
                                       stopindx = (nodestring.Substring(startindx)).IndexOf('\"');
                                       data = nodestring.Substring(startindx, stopindx);
                                       switch (tag)
                                       {
                                          case "CERTLVL": elem.SetCertLvl(data); break;     
                                          case "CN": if (nodestring[1] == 'S') elem.SetCommonName(true, true, data); if (nodestring[1] == 'I') elem.SetCommonName(false, true, data); break;
                                          case "OU": if (nodestring[1] == 'S') elem.SetOrgUnit(true, true, data); if (nodestring[1] == 'I') elem.SetOrgUnit(false, true, data); break;
                                          case "O": if (nodestring[1] == 'S') elem.SetOrg(true, true, data); if (nodestring[1] == 'I') elem.SetOrg(false, true, data); break;
                                          case "L": if (nodestring[1] == 'S') elem.SetLocation(true, true, data); if (nodestring[1] == 'I') elem.SetLocation(false, true, data); break;
                                          case "S": if (nodestring[1] == 'S') elem.SetState(true, true, data); if (nodestring[1] == 'I') elem.SetState(false, true, data); break;
                                          case "C": if (nodestring[1] == 'S') elem.SetCountry(true, true, data); if (nodestring[1] == 'I') elem.SetCountry(false, true, data); break;
                                       }
                                    }

                                 }


                                 CustomerList.Add(elem);
                              }
                           }
                        }
                     }
                  }
               }
            }
         }
         catch (Exception ex) { Console.WriteLine(ex.Message); throw (ex); }
      }

      public static List<WhiteListElement>CustomerList = null;

      static void Main(string[] args)
      {
         CustomerList = new List<WhiteListElement>();
         CreateWhiteList();
      }
   }
}

------------- Code snippet end。

将第一个元素放入列表(CustomerList.Add(elem))并返回到“WhiteListElement elem = new WhiteListElement();”行后出现问题。这将删除CustomerList [0]中的元素,并且在将数据放入elem之后,它将被插入elem和CustomerList [0],最后在列表中以两个相同的元素结束。

我甚至试图在添加elem之后添加elem = null只是为了尝试擦除引用,但是这不起作用

我做错了什么?

/卡斯滕

2 个答案:

答案 0 :(得分:2)

  private static string[,] Subject;  
  private static string[,] Issuer;   

  private static string MinTlsLevel; 
  private static string Customer;

你的问题来自这里,静态成员通过类的所有实例共享,因此当你编辑第二个时,你擦除第一个,你的类应该是这样的

public class WhiteListElement
   {
      private const byte EQL = 0;  
      private const byte CTN = 1;  
      private const byte COMMON_NAME = 0;  
      private const byte ORG = 1;  
      private const byte ORG_UNIT = 2;  
      private const byte LOC = 3;  
      private const byte STATE = 4; 
      private const byte COUNTRY = 5;   

      private string[,] Subject;  
      private string[,] Issuer;   

      private string MinTlsLevel; 
      private string Customer;


      public WhiteListElement()
      {
         Subject = new string[6, 2];
         Issuer = new string[6, 2];
         Customer = "";
         MinTlsLevel = "";
      }

      //---- set/get functions ---- example
      public string GetCommonName(bool SubjectVal, bool Name)
      {  
         if (true == SubjectVal) { if (true == Name) return Subject[COMMON_NAME, 0]; else return Subject[COMMON_NAME, 1]; }
         else { if (true == Name) return Issuer[COMMON_NAME, 0]; else return Issuer[COMMON_NAME, 1]; }
      }
      public void SetCommonName(bool SubjectVal, bool Name, string NewValue)
      {  
         if (true == SubjectVal) { if (true == Name) Subject[COMMON_NAME, 0] = NewValue; else Subject[COMMON_NAME, 1] = NewValue; }
         else { if (true == Name) Issuer[COMMON_NAME, 0] = NewValue; else Issuer[COMMON_NAME, 1] = NewValue; }
      }

   }

编辑:您可以在参考资料中阅读有关静态的更多内容:https://msdn.microsoft.com/fr-fr/library/98f28cdx.aspx

特别是:

  

虽然类的实例包含该类的所有实例字段的单独副本,但每个静态字段只有一个副本。

     

无法使用它来引用静态方法或属性访问器。

答案 1 :(得分:1)

首先,我认为Boo的答案可以解决您的问题,但我认为我至少会建议采用更加面向对象的方法,以便将来更轻松地使用/调试此问题:

cmd.exe

可以用作:

public class WhiteListElement
{
    public string CertLevel;

    public static WhiteListElement Create(XElement xml)
    {
        WhiteListElement element = new WhiteListElement();
        element.CertLevel = xml.Attribute("CERTLVL").Value;
        // Put data into object...
        return element;
    }
}

public class WhiteList
{
    public List<WhiteListElement> Elements = new List<WhiteListElement>();

    public static WhiteList Create(string xmlUri)
    {
        WhiteList whiteList = new WhiteList();
        whiteList.Elements.AddRange(XElement.Load(xmlUri).Descendants("Kunder")
            .Where(xmlElement => xmlElement != null)
            .Select(xmlElement => WhiteListElement.Create(xmlElement)));
        return whiteList;
    }
}

使用示例XML:

WhiteList list = WhiteList.Create("WhiteList.xml");
string certLevel1 = list.Elements[0].CertLevel;