加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

vb.net – 使用Color作为可选参数在类中的函数中

发布时间:2020-12-17 00:18:03 所属栏目:大数据 来源:网络整理
导读:如何在某个函数或子函数中声明一个可选的颜色参数,就像我以正常方式那样做(我的意思是为该可选参数提供一些默认颜色),因为vb.net编译器抱怨它有一些错误码.我该如何解决这个问题. 示例代码如下: Public Shared Function SomeFunction(ByVal iParam As Integ
如何在某个函数或子函数中声明一个可选的颜色参数,就像我以正常方式那样做(我的意思是为该可选参数提供一些默认颜色),因为vb.net编译器抱怨它有一些错误码.我该如何解决这个问题.
示例代码如下:
Public Shared Function SomeFunction(ByVal iParam As Integer,Optional ByVal oColor As Color = Color.Black)

        End Function

编译器不接受’= Color.Black’

MSDN对Visual Basic说约 Optional Parameters

For each optional parameter,you must specify a constant expression as
the default value of that parameter. If the expression evaluates to
Nothing,the default value of the value data type is used as the
default value of the parameter.

所以你不能使用那种语法,相反你可以写这样的东西

Private Sub Test(a As Integer,Optional c As Color = Nothing)
    If c = Nothing Then
        c = Color.Black ' your default color'
    End If
    ......
End Sub

用C#编写的相同代码如下

private void Test(int a,Color c = default(Color))
{
    if (c.IsEmpty)
        c = Color.Black;
}

在C#中,您无法针对空值测试值类型(如颜色,点,大小等…).这些类型永远不会为null,但它们具有类型的默认值 – (对于整数类似0),因此,如果您需要为值类型传递可选参数,则可以使用new关键字创建它,并使用值喜欢使用默认值或使用default keyword,让框架决定哪个值是该类型的默认值.如果让框架选择,那么IsEmpty属性将为true.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读