2021年3月27日土曜日

VB.net での nothing (null) の扱い

勝手に初期値に変換される!

Dim dt as Date = nothing
としても dt は初期値がセットされている (nothingではない)
if (dt is Nothing) then
 → エラー

Nothing を許容するには
Dim dt? as Date = nothing  
変数名のおしりに"?" をつけると nothing が代入できる
if (dt is Nothing) then
 → OK


Date型またはNothingを返す関数
Function GetDate() as Nullable(of Date)


Databaseへの登録
Nothing と DBNull.value は異なる

adoCmd.parameter.Add("DATE_VALUE",type.date).value = IIf (dt is nothing, DBNull.value, dt)

-------------------------------------------------------------

Sub Test() 
    Dim dt1 As Date = Nothing
    Dim dt2? As Date = Nothing

    'If (dt1 Is Nothing) Then
    '    Console.WriteLine("dt1 is nothing")
    'End If
    If (dt2 Is Nothing) Then
        Console.WriteLine("dt2 is nothing")
    End If

    Console.WriteLine(String.Format("value1: {0}", dt1.ToString()))
    Console.WriteLine(String.Format("value2: {0}", dt2.ToString()))

    Console.WriteLine(String.Format("F1: {0}", F1().ToString()))
    Console.WriteLine(String.Format("F2: {0}", F2().ToString()))
End Sub

Function F1() As Date
    Return Nothing
End Function

Function F2() As Nullable(Of Date)
    Return Nothing
End Function

0 件のコメント: