How do I use DateTime.TryParse with a Nullable?

前端 未结 9 643
逝去的感伤
逝去的感伤 2020-12-02 15:06

I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:

DateTime? d;
bool success = DateTime.         


        
9条回答
  •  春和景丽
    2020-12-02 15:22

    You can't because Nullable is a different type to DateTime. You need to write your own function to do it,

    public bool TryParse(string text, out Nullable nDate)
    {
        DateTime date;
        bool isParsed = DateTime.TryParse(text, out date);
        if (isParsed)
            nDate = new Nullable(date);
        else
            nDate = new Nullable();
        return isParsed;
    }
    

    Hope this helps :)

    EDIT: Removed the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the "this" parameter will not work with Value Types.

    P.S. The Bad Hoor in question is an old friend :)

提交回复
热议问题