0

私はNullableが初めてです。私はC#でDateTimeをnullにしたいので、try-catchで値を割り当て、その後nullかどうかを確認します。

コード:

DateTime? dt = null;
try
{
    dt = DateTime.ParseExact(stringDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
}
catch(FormatException)
{
    Console.WriteLine("The given string is not valid and could not be converter to a DateTime");
}
// Check if the DateTime is not null
// If it's not null, do something with the DateTime

だから、私の質問:

どちらを使用する必要があるか、なぜ使用する必要があるか、両方の違いは何ですか。

if(dt != null)
{
    doSomethingWithDateTime(dt);
}

または:

if(dt.HasValue)
{
    doSomethingWithDateTime(dt.Value);
}
4

0 に答える 0