You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 向List添加账户时原有元素被覆盖问题求助

问题核心原因

  • 你定义的Accounts存储容器是Account类的实例字段,没有添加static静态修饰,每次创建新的Account对象时,都会重新执行初始化逻辑生成一个全新的空List,之前存储的内容自然就被"覆盖"了
  • 同时你的CreateAccount、PrintAccounts都是静态方法,静态方法无法直接访问非静态的实例成员,你的原始代码本身存在编译错误,你能运行的版本大概率是在静态方法里每次都新建了Account实例,相当于每次操作的都是不同的List容器

修复后的可运行代码

using System;
using System.Collections.Generic;

namespace Assignment_List_Test
{
    // 单独定义Account实体类,只存账户属性
    public class Account
    {
        public string Username { get; set; }
        public string UserEmail { get; set; }
        public string UserPassword { get; set; }
    }

    public class AccountView
    {
        // 给AccountList加默认初始化,避免空引用
        public List<Account> AccountList { get; set; } = new List<Account>();
    }

    // 单独放置程序入口和业务逻辑,避免职责混乱
    class Program
    {
        // 把存储容器改成静态成员,整个程序运行期间只会初始化一次
        static AccountView Accounts = new AccountView();

        static void Main(string[] args)
        {
            // 可多次调用CreateAccount验证不会覆盖原有数据
            CreateAccount();
            CreateAccount();
            PrintAccounts();
        }

        static void CreateAccount()
        {
            Console.Write("Username: ");
            string userNameInput = Console.ReadLine();
            Console.Write("Email: ");
            string userEmailInput = Console.ReadLine();
            Console.Write("Password: ");
            string userPasswordInput = Console.ReadLine();

            var newAccount = new Account
            {
                Username = userNameInput,
                UserEmail = userEmailInput,
                UserPassword = userPasswordInput
            };

            Accounts.AccountList.Add(newAccount);
            Console.WriteLine("账户创建成功\n");
        }

        static void PrintAccounts()
        {
            Console.WriteLine("=== 所有账户信息 ===");
            foreach (var account in Accounts.AccountList)
            {
                Console.WriteLine("Username: {0}, UserEmail: {1}, UserPassword: {2}", account.Username, account.UserEmail, account.UserPassword);
            }
        }
    }
}

关键修改说明

  • 拆分了原本揉在Account类里的实体属性、业务逻辑、程序入口,避免职责混乱导致的成员归属错误
  • 将存储账户的Accounts容器改为静态成员,整个程序运行周期内只会初始化一次,每次调用CreateAccount都是往同一个List里追加内容,不会生成新的空容器
  • 给AccountView的AccountList属性添加了默认初始化逻辑,避免手动初始化遗漏导致的空引用异常

内容的提问来源于stack exchange,提问作者Tronthepom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 09:15:04