问题
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