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

如何在C#中利用主构造函数特性实现多构造函数并设置默认值?

问题原因与解决方法

你使用的是C# 9及以上版本的主构造函数语法,这种语法下,类的所有自定义构造函数必须显式调用主构造函数,否则编译器会报错。同时,你定义的Name和Age是init修饰的只读属性,直接在新构造函数中赋值会和主构造的初始化逻辑冲突。

解决方法一:调用主构造函数(推荐)

在新增的单参数构造函数中,通过: this(name, 18)显式调用主构造函数,传递默认年龄值18,复用主构造的初始化逻辑:

public class User(string name, int age)
{
    public string Name { get; init; } = name;
    public int Age { get; init; } = age;

    // 调用主构造函数,传入默认年龄18
    public User(string name) : this(name, 18)
    {
    }
}

解决方法二:改用常规构造函数写法

如果不需要主构造函数的简洁性,可以将类改为常规的构造函数定义方式,直接在每个构造函数中初始化属性:

public class User
{
    public string Name { get; init; }
    public int Age { get; init; }

    public User(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public User(string name)
    {
        Name = name;
        Age = 18;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:27:05