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

如何为C#中Point类型参数设置非null的默认值?

解决Point类型参数默认值导致null的问题

方法1:用空合并运算符处理null参数

在Rectangle的构造函数里,通过??空合并运算符判断传入的p是否为null,若为null则替换为默认的Point实例,既保留可选参数的便利性,又避免start被赋值为null:

public Rectangle(Point p = null, double w = 0, double h = 0)
{
    this.start = p ?? new Point();
    this.width = w;
    this.height = h;
}

方法2:重载构造函数

定义多个构造函数覆盖不同参数场景,完全避免使用null作为默认值:

// 无参构造,使用所有默认值
public Rectangle()
{
    this.start = new Point();
    this.width = 0;
    this.height = 0;
}

// 仅传入起始点的构造
public Rectangle(Point p)
{
    // 额外做null检查,防止外部传入null
    this.start = p ?? new Point();
    this.width = 0;
    this.height = 0;
}

// 传入所有参数的构造
public Rectangle(Point p, double w, double h)
{
    this.start = p ?? new Point();
    this.width = w;
    this.height = h;
}

方法3:直接将默认值设为new Point()(C# 6+支持)

如果项目使用C# 6或更高版本,可以直接把p的默认值设为new Point(),调用构造函数时不传入p会自动使用新的默认Point实例:

public Rectangle(Point p = new Point(), double w = 0, double h = 0)
{
    this.start = p;
    this.width = w;
    this.height = h;
}

注意:这种方式每次调用无参构造时都会创建新的Point实例,若希望所有无参构造的Rectangle共享同一个默认Point,建议用方法1或方法2。

内容的提问来源于stack exchange,提问作者Phú Huỳnh Gia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:35:42