IT story

Nullable과 함께 DateTime.TryParse를 사용하는 방법

hot-time 2020. 8. 4. 22:50
반응형

Nullable과 함께 DateTime.TryParse를 사용하는 방법?


DateTime.TryParse 메서드를 사용하여 문자열의 날짜 시간 값을 Nullable로 가져 오려고합니다. 그러나 이것을 시도하면 :

DateTime? d;
bool success = DateTime.TryParse("some date text", out (DateTime)d);

컴파일러가 알려줍니다

'out'인수는 변수로 분류되지 않습니다

내가 여기서해야 할 일이 확실하지 않습니다. 나는 또한 시도했다 :

out (DateTime)d.Value 

그리고 그것은 작동하지 않습니다. 어떤 아이디어?


DateTime? d=null;
DateTime d2;
bool success = DateTime.TryParse("some date text", out d2);
if (success) d=d2;

(더 우아한 솔루션이있을 수 있지만 단순히 위와 같이 무엇을하지 않습니까?)


Jason이 말했듯이 올바른 유형의 변수를 만들어 전달할 수 있습니다. 자신의 방법으로 캡슐화하고 싶을 수도 있습니다.

public static DateTime? TryParse(string text)
{
    DateTime date;
    if (DateTime.TryParse(text, out date))
    {
        return date;
    }
    else
    {
        return null;
    }
}

... 또는 조건 연산자를 좋아하는 경우 :

public static DateTime? TryParse(string text)
{
    DateTime date;
    return DateTime.TryParse(text, out date) ? date : (DateTime?) null;
}

또는 C # 7에서 :

public static DateTime? TryParse(string text) =>
    DateTime.TryParse(text, out var date) ? date : (DateTime?) null;

다음은 Jason이 제안한 내용의 약간 간결한 버전입니다.

DateTime? d; DateTime dt;
d = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;

Nullable<DateTime>와 다른 유형 이기 때문에 할 수 없습니다 DateTime. 이를 위해서는 자신의 함수를 작성해야합니다.

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

도움이 되었기를 바랍니다 :)

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 :)


What about creating an extension method?

public static class NullableExtensions
{
    public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)
    {
        DateTime tempDate;
        if(! DateTime.TryParse(dateString,out tempDate))
        {
            result = null;
            return false;
        }

        result = tempDate;
        return true;

    }
}

I don't see why Microsoft didn't handle this. A smart little utility method to deal with this (I had the issue with int, but replacing int with DateTime will be the same effect, could be.....

    public static bool NullableValueTryParse(string text, out int? nInt)
    {
        int value;
        if (int.TryParse(text, out value))
        {
            nInt = value;
            return true;
        }
        else
        {
            nInt = null;
            return false;
        }
    }

Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:

DateTime? d = DateTime.Parse("some valid text");

Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.

참고URL : https://stackoverflow.com/questions/192121/how-do-i-use-datetime-tryparse-with-a-nullabledatetime

반응형