Using Color As Optional Parameter In a function within a class

后端 未结 4 1270
轮回少年
轮回少年 2021-01-11 16:09

How can I declare an optional color parameter in some function or sub, as if I do that in the normal way (I mean to give some default color for that optional parameter) as t

4条回答
  •  一向
    一向 (楼主)
    2021-01-11 17:03

    MSDN says about Optional Parameters for Visual Basic

    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.

    So you can't use that syntax, instead you could write something like this

    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
    

    The same code written in C# is the following

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

    In C# you cannot test a Value type (like Color, Point, Size etc...) against a null value. These types are never null, but they have a default value for the type-(Like 0 for integers), so, if you need to pass an optional parameter for a value type you could create it with the new keyword with the values you would like to use as default or use the default keyword and let the framework decide which value is the default for the type. If you let the framework choose then the IsEmpty property will be true.

提交回复
热议问题