nullable int와 함께 int.TryParse를 사용하는 방법? [복제]
이 질문에 이미 답변이 있습니다.
문자열 값이 정수인지 찾기 위해 TryParse를 사용하려고합니다. 값이 정수이면 foreach 루프를 건너 뜁니다. 다음은 내 코드입니다.
string strValue = "42 "
if (int.TryParse(trim(strValue) , intVal)) == false
{
break;
}
intVal은 int? (nullable INT) 유형의 변수입니다. nullable int와 함께 Tryparse를 어떻게 사용할 수 있습니까?
불행히도 다른 변수를 사용하지 않고는이 작업을 수행 할 수 없습니다. out
인수 유형이 매개 변수와 정확히 일치해야 하기 때문 입니다.
Daniel의 코드와 비슷하지만 두 번째 인수, 트리밍 및 부울 상수와의 비교 방지 측면에서 수정되었습니다.
int tmp;
if (!int.TryParse(strValue.Trim(), out tmp))
{
break;
}
intVal = tmp;
TryParse를 사용하는 nullable int에 대한 옵션은 다음과 같습니다.
public int? TryParseNullable(string val)
{
int outValue;
return int.TryParse(val, out outValue) ? (int?)outValue : null;
}
제네릭 버전을 생산하는 것을 막을 수 없습니다. 아래 사용법.
public class NullableHelper
{
public delegate bool TryDelegate<T>(string s, out T result);
public static bool TryParseNullable<T>(string s, out T? result, TryDelegate<T> tryDelegate) where T : struct
{
if (s == null)
{
result = null;
return true;
}
T temp;
bool success = tryDelegate(s, out temp);
result = temp;
return success;
}
public static T? ParseNullable<T>(string s, TryDelegate<T> tryDelegate) where T : struct
{
if (s == null)
{
return null;
}
T temp;
return tryDelegate(s, out temp)
? (T?)temp
: null;
}
}
bool? answer = NullableHelper.ParseNullable<bool>(answerAsString, Boolean.TryParse);
nullable 값을 구문 분석하는 도우미 메서드를 만들 수 있습니다.
Example Usage:
int? intVal;
if( !NullableInt.TryParse( "42", out intVal ) )
{
break;
}
Helper Method:
public static class NullableInt
{
public static bool TryParse( string text, out int? outValue )
{
int parsedValue;
bool success = int.TryParse( text, out parsedValue );
outValue = success ? (int?)parsedValue : null;
return success;
}
}
You could also make an extension method for this purpose;
public static bool TryParse(this object value, out int? parsed)
{
parsed = null;
try
{
if (value == null)
return true;
int parsedValue;
parsed = int.TryParse(value.ToString(), out parsedValue) ? (int?)parsedValue : null;
return true;
}
catch (Exception)
{
return false;
}
}
I've made this an extension on the object
type, but it could equally well be on string
. Personally I like these parser-extensions to be available on any object hence the extension on object
instead of string
.
Example of use:
[TestCase("1", 1)]
[TestCase("0", 0)]
[TestCase("-1", -1)]
[TestCase("2147483647", int.MaxValue)]
[TestCase("2147483648", null)]
[TestCase("-2147483648", int.MinValue)]
[TestCase("-2147483649", null)]
[TestCase("1.2", null)]
[TestCase("1 1", null)]
[TestCase("", null)]
[TestCase(null, null)]
[TestCase("not an int value", null)]
public void Should_parse_input_as_nullable_int(object input, int? expectedResult)
{
int? parsedValue;
bool parsingWasSuccessfull = input.TryParse(out parsedValue);
Assert.That(parsingWasSuccessfull);
Assert.That(parsedValue, Is.EqualTo(expectedResult));
}
The downside would be that this breaks with the frameworks syntax for parsing values;
int.TryParse(input, out output))
But I like the shorter version of it (whether it's more readable or not might be subject to discussion);
input.TryParse(out output)
참고URL : https://stackoverflow.com/questions/3390750/how-to-use-int-tryparse-with-nullable-int
'Programing' 카테고리의 다른 글
pandas DataFrame으로 SQLAlchemy ORM 변환 (0) | 2020.09.09 |
---|---|
TFS 소스 제어에서 특정 파일을 제외하는 방법 (0) | 2020.09.09 |
C #을 사용하여 파일 확장명 변경 (0) | 2020.09.09 |
MsDeploy가 403 금지를 반환합니다. (0) | 2020.09.09 |
Android에서 콘텐츠 제공 업체를 사용하여 여러 테이블을 노출하는 모범 사례 (0) | 2020.09.08 |