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

C#如何获取类构造函数生成的所有实例对象的属性参数

解决方案

方案1:使用集合存储账户实例(最常用)

直接把所有创建的Account实例存入泛型集合,就可以随意遍历、查询,不需要单独指定每个实例名,修改后的代码如下:

class Account
{
    public string customerName;
    public string pin;
    public int balance;

    public Account(string accCustomerName, string accPin, int accBalance)
    {
        customerName = accCustomerName;
        pin = accPin;
        balance = accBalance;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    // 初始化泛型集合存储所有账户实例
    List<Account> accounts = new List<Account>
    {
        new Account("Henry_Adobe", "2316", 10000),
        new Account("Patrick_Boka", "3198", 15000),
        new Account("Fred_Simp", "8768", 20000),
        new Account("Derek_Black", "7645", 25000)
    };

    string inputPin = txtInput.Text.Trim();
    Account loginAccount = null;
    // 遍历集合匹配pin
    foreach (var acc in accounts)
    {
        if (acc.pin == inputPin)
        {
            loginAccount = acc;
            break;
        }
    }

    if (loginAccount != null)
    {
        MessageBox.Show($"登录成功!欢迎您,{loginAccount.customerName}");
    }
    else
    {
        MessageBox.Show("pin码错误,登录失败");
    }

    // 更简洁的写法:用LINQ查询,需要先引入命名空间 using System.Linq;
    // var loginAccount = accounts.FirstOrDefault(a => a.pin == inputPin);
}

方案2:使用静态集合自动托管所有实例

如果需要在整个项目全局访问所有账户,可以在Account类内添加静态集合,创建实例时自动收录,不需要手动维护集合:

class Account
{
    // 静态集合存储所有Account实例,全局可访问
    public static List<Account> AllAccounts = new List<Account>();

    public string customerName;
    public string pin;
    public int balance;

    public Account(string accCustomerName, string accPin, int accBalance)
    {
        customerName = accCustomerName;
        pin = accPin;
        balance = accBalance;
        // 构造函数执行时自动把当前实例加入静态集合
        AllAccounts.Add(this);
    }
}

// 后续任意位置需要遍历所有账户,直接访问 Account.AllAccounts 即可

可选优化:使用字典提升查询效率

如果账户数量较多,用Dictionary<string, Account>存储,以pin为key,查询时间复杂度为O(1),比遍历列表更快:

// 初始化字典
Dictionary<string, Account> accountDict = new Dictionary<string, Account>();
var acc = new Account("测试用户", "1234", 1000);
accountDict.Add(acc.pin, acc);

// 查询时直接判断是否存在对应pin
string inputPin = txtInput.Text.Trim();
if (accountDict.TryGetValue(inputPin, out var loginAcc))
{
    MessageBox.Show("登录成功");
}

注意事项

  • 生产环境禁止明文存储pin码,需使用SHA256等算法加密存储,验证时将用户输入的pin加密后再比对
  • 注意处理pin重复的场景,避免字典添加时抛出冲突异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 16:48:02