質問

値が整数かどうかをテストするためにInteger.TryParseを使用する必要があることがよくあります。ただし、TryParseを使用する場合、関数に参照変数を渡す必要があるため、渡すために常に空白整数を作成する必要があります。通常は次のようになります。

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

私が望むのは単純なTrue / False応答だけであることを考えると、これは非常に面倒です。これにアプローチするより良い方法はありますか?なぜテストしたい値を渡してtrue / false応答を取得するだけのオーバーロード関数がないのですか?

役に立ちましたか?

解決

整数を宣言する必要はありません。

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

申し訳ありませんが、私は知っていますが、これを.Net 3.5のMyExtensionsクラスに追加することもできます。検証が必要でない限り心配する必要はありません。

<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.Netを書いていませんが、ここに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);
  }
}

J Ambrose Little 2003年のIsNumericチェックのタイミングテスト。 CLR v2で上記のテストを再試行することもできます。

バリエーションは次のとおりです。

Int32.TryParse(input_string, Globalization.NumberStyles.Integer)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top