为什么不能点,矩形作为可选参数?矩形、可选、参数

2023-09-04 09:55:03 作者:称霸幼儿园

我想要一个可选的参数传递给一个几何函数,名为偏移,这可能会或可能不会进行规定,但是C#不允许我这样做以下任一。有没有办法做到这一点?

I'm trying to pass an optional argument to a geometry function, called offset, which may or may not be specified, but C# doesn't allow me to do any of the following. Is there a way to accomplish this?

Null作为默认

错误:类型'值'不能用作默认参数,因为没有标准转换到类型System.Drawing.Point

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) {}

空默认

错误:偏移必须是一个编译时间常数默认参数值

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

public void LayoutRelative(.... Point offset = Point.Empty) {}

推荐答案

如果您的默认值,不需要任何特殊的初始化,你并不需要使用可空类型,或者创建不同的重载。 您可以使用默认关键字:

If your default value doesn't require any special initialization, you don't need to use a nullable type or create different overloads. You can use the default keyword:

public void LayoutRelative(.... Point offset = default(Point)) {}

如果你想使用可空类型,而不是:

If you want to use a nullable type instead:

public void LayoutRelative(.... Point? offset = null)
{
    if (offset.HasValue)
    {
        DoSomethingWith(offset.Value);
    }
}