programing

정수.파스 - 더 좋은 방법?

telecom 2023. 5. 20. 10:07
반응형

정수.파스 - 더 좋은 방법?

저는 종종 Integer를 사용해야 합니다.값이 정수인지 여부를 테스트하려면 구문 분석을 시도합니다.하지만 TryParse를 사용할 때는 함수에 참조 변수를 전달해야 하므로 전달할 빈 정수를 항상 만들어야 합니다.일반적으로 다음과 같이 나타납니다.

Dim tempInt as Integer
If Integer.TryParse(myInt, tempInt) Then

제가 원하는 것이 단순한 참/거짓 응답이라는 점을 고려하면 이 작업은 상당히 번거롭습니다.이것에 접근하는 더 좋은 방법이 있습니까?테스트할 값을 전달하고 참/거짓 응답을 받을 수 있는 오버로드 기능이 없는 이유는 무엇입니까?

정수를 선언할 필요가 없습니다.

If Integer.TryParse(intToCheck, 0) Then

또는

If Integer.TryParse(intToCheck, Nothing) Then

만약에.Net 3.5 기능 문자열에 대한 확장 메서드를 만들 수 있습니다.

Public Module MyExtensions

    <System.Runtime.CompilerServices.Extension()> _
    Public Function IsInteger(ByVal value As String) As Boolean
        If String.IsNullOrEmpty(value) Then
            Return False
        Else
            Return Integer.TryParse(value, Nothing)
        End If
    End Function

End Module

그리고 다음과 같이 전화합니다.

If value.IsInteger() Then

죄송합니다. 정신이 팔려 있는 것은 알지만, 의 위의 MyExtensions 클래스에 이 정보를 추가할 수도 있습니다.Net 3.5. 검증이 필요하지 않으면 걱정하지 마십시오.

<System.Runtime.CompilerServices.Extension()> _
Public Function ToInteger(ByVal value As String) As Integer
    If value.IsInteger() Then
        Return Integer.Parse(value)
    Else
        Return 0
    End If
End Function

그런 다음 간단히 사용합니다.

value.ToInteger()

올바른 정수가 아닌 경우 0을 반환합니다.

VB.net 을 사용하고 있으므로 IsNumeric 기능을 사용할 수 있습니다.

If IsNumeric(myInt) Then
    'Do Suff here
End If
public static class Util {

    public static Int32? ParseInt32(this string text) {
        Int32 result;
        if(!Int32.TryParse(text, out result))
            return null;
        return result;
    }

    public static bool IsParseInt32(this string text) {
        return text.ParseInt32() != null;
    }

}

이 코드를 사용해 보십시오.

Module IntegerHelpers

  Function IsInteger(ByVal p1 as String) as Boolean
    Dim unused as Integer = 0
    return Integer.TryParse(p1,unused)
  End Function
End Module

좋은 점은 모듈 수준의 기능으로 선언되었기 때문에 한정자 없이 사용할 수 있다는 것입니다.사용 예

return IsInteger(mInt)

코드를 정리하기 위해 확장 방법을 쓰는 것이 어떻습니까?VB는 안 썼어요.잠시 동안 인터넷을 사용하지만, 다음은 c#의 예입니다.

public static class MyIntExtensionClass
{
  public static bool IsInteger(this string value)
  {
    if(string.IsNullOrEmpty(value))
      return false;

    int dummy;
    return int.TryParse(value, dummy);
  }
}

Jambrose Little은 2003년에 IsNumeric 검사에 대한 타이밍 테스트를 수행했습니다.CLR의 v2를 사용하여 언급된 테스트를 다시 시도할 수 있습니다.

변형은 다음과 같습니다.

Int32.TryParse(input_string, Globalization.NumberStyles.Integer)

언급URL : https://stackoverflow.com/questions/419027/integer-tryparse-a-better-way

반응형