Why can't Point and Rectangle be used as optional parameters?

这一生的挚爱 提交于 2019-12-10 14:59:16

问题


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:


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


来源:https://stackoverflow.com/questions/12235653/why-cant-point-and-rectangle-be-used-as-optional-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!