简体   繁体   English

DateTime.TryParse不接受可为空的DateTime?

[英]DateTime.TryParse doesn't accept nullable DateTime?

so I have this nullable variable I created: 所以我创建了这个可以为空的变量:

private DateTime? _startDate;

I wanted to parse some variable to DateTime and then assign it to this variable, but the VS complains that the TryParse method has some invalid arguments. 我想将一些变量解析为DateTime,然后将其分配给此变量,但VS抱怨TryParse方法有一些无效的参数。

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
        {
            DateTime.TryParse(Request.Form["StartDate"], out _startDate);
        }
        else
        { _startDate = null; }

Is there a syntax error I have or I can't use nullable variables in here? 我有语法错误或者我不能在这里使用可空变量吗?

As others have said, they're not compatible types. 正如其他人所说,他们不是兼容的类型。 I would suggest you create a new method which wraps DateTime.TryParse and returns a Nullable<DateTime> : 我建议你创建一个新方法,它包装DateTime.TryParse返回一个Nullable<DateTime>

// Add appropriate overloads to match TryParse and TryParseExact
public static DateTime? TryParseNullableDateTime(string text)
{
    DateTime value;
    return DateTime.TryParse(text, out value) ? value : (DateTime?) null;
}

Then you can just use: 然后你可以使用:

_startDate = Helpers.TryParseNullableDateTime(Request.Form["StartDate"]);

(No need to check for null or empty string; TryParse will just return false in that case anyway.) (无需检查null或空字符串;无论如何, TryParse只返回false。)

No, DateTime.TryParse() doesn't accept DateTime? 不, DateTime.TryParse()不接受DateTime? because DateTime? 因为DateTime? is really Nullable<DateTime> - not a compatible type. 是否可以为Nullable<DateTime> - 不是兼容的类型。

Try this instead: 试试这个:

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
    {
        var dtValue = new DateTime();
        if (DateTime.TryParse(Request.Form["StartDate"], out dtValue)) {
            _startDate = dtValue;
        }
        else {
            _startDate = null;
        }
    }
    else
    { _startDate = null; }

DateTime? and DateTime are different and non-compatible types in relation to out . DateTime是不同的,不兼容的类型与out So you need to use DateTime and then copy value as in Yuck's answer. 所以你需要使用DateTime然后复制值,就像在Yuck的答案中一样。

Here's the code. 这是代码。 Exception is been handled. 已处理例外情况。

if (string.IsNullOrEmpty(Request.Form["StartDate"]) == false)
        {
            DateTime strtDate;
            try
              {
                strtDate = Convert.ToDateTime(Request.Form["StartDate"]);
                _startDate = strtDate;
              }
            catch(Exception)
              {
               _startDate = null;
              }
         }
        else
        { 
       _startDate = null;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM