代码之家  ›  专栏  ›  技术社区  ›  callisto

在foreach循环中编辑列表

  •  2
  • callisto  · 技术社区  · 16 年前

    class Client
    {
    - int ID
    - int? ParentID
    - string Name
    - datetime CreateDate
    - int ACClientID
    - List <Client> Clients }
    

     private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
            {
                client.ACClientID = ACClientID;
    
                foreach (ATBusiness.Objects.Client child in client.Clients)
                {
                    AssignToChildren(ref child, ACClientID);
                }
            }
    

    [编辑]我看过 What is the best way to modify a list in a 'foreach' loop?

    4 回复  |  直到 9 年前
        1
  •  11
  •   AnthonyWJones    16 年前

    由于您从未为参数赋值 client ref .

    由于您没有修改 List<T> 对象本身,即使在枚举过程中,也没有理由不能修改ACCClientID属性。只有当您试图篡改枚举后面的列表成员身份时,才会出现异常。

        2
  •  1
  •   tster    16 年前
        private static bool AssignToChildren(ATBusiness.Objects.Client client, int ACClientID)
        {
            client.ACClientID = ACClientID;
    
            foreach (ATBusiness.Objects.Client child in client.Clients)
            {
                AssignToChildren(child, ACClientID);
            }
        }
    
        3
  •  0
  •   bruno conde    16 年前

    class Client
    {
        public Client()
        {
            Clients = new List<Client>();
        }
    
        public List<Client> Clients { get; private set; }
    
        private int aCClientID;
    
        public int ACClientID
        {
            get { return aCClientID; }
            set { aCClientID = value; }
        }
    
        public int ACClientIDRecursive
        {
            get
            {
                return aCClientID;
            }
            set
            {
                aCClientID = value;
                foreach (var c in Clients)
                {
                    c.ACClientIDRecursive = value;
                }
            }
        }
    }
    
        4
  •  -2
  •   Sani Huttunen    16 年前

    private static bool AssignToChildren(ref ATBusiness.Objects.Client client, int ACClientID)
    {
      client.ACClientID = ACClientID;
      for (int i = client.Clients.Count - 1; i >= 0; i--) 
      {
        AssignToChildren(ref client.Clients[i], ACClientID);
      }
    }
    
    推荐文章