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

C#如何判断类实例构造函数参数是否赋值 空值替换为unknown

解决方案

你当前代码中的Father、Mother属于string引用类型字段,未显式赋值时默认值为null,可以通过空值判断逻辑检测未赋值状态,具体实现可以选以下两种方案:


方案1:在输出方法中直接做空值替换(无需修改原有初始化逻辑)

直接修改DogsOverall方法,使用C#的空合并运算符??或者string.IsNullOrEmpty()方法判断空值并替换为unknown:

改后代码示例:

public string DogsOverall()
{
    // 写法1:仅替换null值,用空合并运算符
    return $"Name {Name}, sex {Sex}, fathers name is {Father ?? "unknown"}, mothers name is {Mother ?? "unknown"}";

    // 写法2:同时兼容null和空字符串的情况,按需选用
    // return $"Name {Name}, sex {Sex}, fathers name is {string.IsNullOrEmpty(Father) ? "unknown" : Father}, mothers name is {string.IsNullOrEmpty(Mother) ? "unknown" : Mother}";
}

方案2:字段声明时直接设置默认值(从源头避免空值)

如果要求所有未传入父/母亲信息的Dog实例默认都显示unknown,直接在字段声明时赋值即可,不用额外写判空逻辑:

改后代码示例:

public class Dog
{
    public string Name;
    public string Sex;
    // 字段默认值设为unknown
    public string Father = "unknown";
    public string Mother = "unknown";

    public Dog(string name, string sex)
    {
        Name = name;
        Sex = sex;
    }

    public Dog(string name, string sex, string father, string mother)
    {
        Father = father;
        Mother = mother;
        Name = name;
        Sex = sex;
    }

    public string DogsOverall()
    {
        // 这里不需要额外判空,字段已经有默认值
        return $"Name {Name}, sex {Sex}, fathers name is {Father}, mothers name is {Mother}";
    }
}

单独检测字段是否未赋值的方法

如果需要单独判断某个字段的赋值状态,直接调用空值判断方法即可:

Dog dog = new Dog("阿黄", "公");
// 判断Father是否未赋值
if (string.IsNullOrEmpty(dog.Father))
{
    // 执行未赋值对应的逻辑处理
}

内容的提问来源于stack exchange,提问作者Dāvis Zemītis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:15:02