为什么Point和Rectangle不能用作可选参数?

5

我正在尝试向称为offset的几何函数传递一个可选参数,该参数可能会被指定,也可能不会被指定,但C#不允许我执行以下任何操作。有没有办法实现这个?

  • Null as default

    Error: A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'System.Drawing.Point'

    public void LayoutRelative(.... Point offset = null) {}
    
  • Empty as default

    Error: Default parameter value for 'offset' must be a compile-time constant

    public void LayoutRelative(.... Point offset = Point.Empty) {}
    
1个回答

16
如果你的默认值不需要任何特殊初始化,就不需要使用可空类型或创建不同的重载。 你可以使用"default"关键字:
public void LayoutRelative(.... Point offset = default(Point)) {}
如果你想使用可空类型:
public void LayoutRelative(.... Point? offset = null)
{
    if (offset.HasValue)
    {
        DoSomethingWith(offset.Value);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接