Why can't Point and Rectangle be used as optio

2019-06-22 07:10发布

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 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条回答
We Are One
2楼-- · 2019-06-22 07:59

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);
    }
}
查看更多
登录 后发表回答