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

C#中类属性Setter未抛出预期异常的问题排查与实现咨询

C# Person类属性验证未触发异常的问题

我来帮你理清楚这个问题的核心所在,以及你关于构造函数异常处理的疑问:

首先,你遇到的根本问题是:构造函数里直接给私有字段this.name赋值了,完全没用到你写了验证逻辑的Name属性的setter!

你看你的构造函数代码:

public person(string Name, string Age, double Weight) {
    this.name = Name; // 这里直接操作私有字段,跳过了属性的setter验证
    this.weight = Weight;
    try {
        this.age = int.Parse(Age);
    } catch (FormatException) {
        WriteLine("Age must be an integer number. Age set to 0 by default.");
        this.age = 0;
    }
}

而你的Name属性的验证逻辑只在setter里,直接给私有字段赋值自然不会触发任何检查,所以哪怕传入"hi"这种无效值,也不会抛出异常。

接下来回答你关于构造函数加try-catch的疑问:这种实现思路本身没有错误,但前提是你得先让属性的验证逻辑执行起来。

修复步骤

  • 修改构造函数,调用属性的setter
    把构造函数里的this.name = Name;改成this.Name = Name;,这样就会触发你写的setter里的验证逻辑了。

  • 处理Name验证的异常
    如果你想在构造函数里捕获并处理这个异常,可以像处理Age的FormatException一样,加try-catch块:

    public person(string Name, string Age, double Weight) {
        try {
            this.Name = Name; // 调用属性setter,触发验证
        } catch (ArgumentException ex) {
            WriteLine($"Invalid name: {ex.Message}. Name set to default value.");
            this.name = "Unknown User"; // 给一个默认值,或者根据需求处理
        }
        this.weight = Weight;
        try {
            this.age = int.Parse(Age);
        } catch (FormatException) {
            WriteLine("Age must be an integer number. Age set to 0 by default.");
            this.age = 0;
        }
    }
    

    当然,如果作业要求必须通过实例化无效对象来测试异常抛出,那也可以不在构造函数里捕获,让异常直接抛出,这样在实例化person p1 = new person("hi", "26", 165);的时候,就会触发你定义的ArgumentException了。

额外小提示

  • 建议把类名person改成Person,符合C#的帕斯卡命名规范,这是行业内的通用约定~
  • 你的Name属性验证条件是长度至少5且包含空格,比如"John Doe"这种是符合要求的,而"hi"或者"JohnDoe"都会触发异常,测试的时候可以用这些案例验证逻辑是否生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 19:22:28