为什么 Point 和 Rectangle 不能作为可选参数? [英] Why can't Point and Rectangle be used as optional parameters?

查看:25
本文介绍了为什么 Point 和 Rectangle 不能作为可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个可选参数传递给名为 offset 的几何函数,该函数可能已指定,也可能未指定,但 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?

  • 默认为空

错误:'' 类型的值不能用作默认参数,因为没有到类型 '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) {}

  • 默认为空

    错误:'offset' 的默认参数值必须是编译时常量

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

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

  • 推荐答案

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

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

    这篇关于为什么 Point 和 Rectangle 不能作为可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆