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

使用switch case展示类中银行客户信息遇类访问及查找问题求助

问题分析与修复方案

核心问题

  1. 类设计冗余:每个客户单独定义类完全没必要,重复代码多,维护困难。
  2. 成员访问权限不足:类内部的name、id、type默认是私有(private),外部无法访问,就算实例化也拿不到数据。
  3. 对象输出错误:直接Console.WriteLine(customer1)只会输出类的完全限定名,不会显示客户信息。
  4. 命名不规范:类名不符合C#大驼峰命名规则,可读性差。

修复后的代码

把重复的客户类合并成一个Customer类,通过构造函数初始化不同客户的数据,同时把成员设为公共属性,重写ToString()方法方便输出:

public class Program
{
    public class Customer
    {
        public string Name { get; }
        public int Id { get; }
        public string Type { get; }

        public Customer(string name, int id, string type)
        {
            Name = name;
            Id = id;
            Type = type;
        }

        // 重写ToString,方便直接输出客户信息
        public override string ToString()
        {
            return $"姓名: {Name}, 客户ID: {Id}, 账户类型: {Type}";
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine("请输入客户ID");
        if (int.TryParse(Console.ReadLine(), out int inputId))
        {
            Customer customer = inputId switch
            {
                101 => new Customer("Akan Udoh", 101, "Current"),
                102 => new Customer("Clara Udoh", 102, "Savings"),
                103 => new Customer("jane doe", 103, "Fixed deposit"),
                _ => null
            };

            if (customer != null)
            {
                Console.WriteLine(customer);
            }
            else
            {
                Console.WriteLine("未找到对应客户");
            }
        }
        else
        {
            Console.WriteLine("输入的ID格式不正确");
        }
    }
}

关键优化点

  • 单一客户类:用一个类封装所有客户的共同属性,通过实例化不同对象存储不同客户数据,避免重复代码。
  • 公共属性:把客户信息设为只读公共属性,既保证外部能访问,又防止数据被意外修改。
  • 安全的输入解析:用int.TryParse替代Convert.ToInt32,避免输入非数字时抛出异常。
  • 模式匹配简化逻辑:用switch表达式替代传统switch,代码更简洁。
  • 重写ToString:直接输出对象就能显示客户信息,无需重复写多个Console.WriteLine。

关于“找不到类”的问题

如果之前出现找不到类的情况,大概率是以下原因:

  • 类的访问修饰符错误(比如不小心设成了private),但你当前代码里的嵌套类是public,所以这个可能性低。
  • 项目文件结构问题,比如类放在了不同的命名空间下,没有添加引用或using语句。但你当前代码是嵌套在Program类里,只要在同一个项目里就不会有这个问题。
  • 编译错误导致类未生成,比如之前的代码有语法错误,编译器没生成对应的类文件,修复语法错误后重新编译即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:21:24