質問

In moving some code over from my test project to the "real" project, which targets Windows CE, some code got embarrassed and turned red in the IDE, namely "TryParse()".

For the lack of ... a horseshoe, the battle was lost; hopefully, the lack of TryParse() will not cause a healthcare.gov-like eCatastrophe; nevertheless is there a better way to rewrite a TryParse() for a TryParseless parser than:

int recCount = 0;
string s = "42";
try {
    recCount = Int32.Parse(s);      
}
catch {
    MessageBox.Show("That was not an int! Consider this a lint-like hint!");
}

?

役に立ちましたか?

解決

Considering s is a string value, you can't cast it to int. If int.TryParse is not available then you can create your own method which would return a bool . Something like:

public static class MyIntConversion
{
    public static bool MyTryParse(object parameter, out int value)
    {
        value = 0;
        try
        {
            value = Convert.ToInt32(parameter);
            return true;
        }
        catch
        {
            return false;
        }
    }
}

and then to use it:

int temp;
if (!MyIntConversion.MyTryParse("123", out temp))
{
     MessageBox.Show("That was not an int! Consider this a lint-like hint!");
}

int.TryParse internally uses try-catch to do parsing and is implemented in similar manner.

他のヒント

public bool TryParseInt32( this string str, out int result )
{
    result = default(int);

    try
    {
        result = Int32.Parse( str );
    }
    catch
    {
        return false;
    }

    return true;
}

usage:

int result;
string str = "1234";

if( str.TryParseInt32( out result ) )
{
}

I'm assuming s is a string. If so, your code won't work. The following code should though:

int recCount = 0;
try {
    recCount = Int32.Parse(s);      
}
catch {
    MessageBox.Show("That was not an int! Consider this a lint-like hint!");
}

You could use a regular expression.

public bool IsNumber(string text)
{
    Regex reg = new Regex("^[0-9]+$");
    bool onlyNumbers = reg.IsMatch(text);
    return onlyNumbers;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top