【问题标题】:What is the best workaround for the lack of TryParse() when targeting WindowsCE?针对 WindowsCE 时缺少 TryParse() 的最佳解决方法是什么?
【发布时间】:2013-11-26 17:47:45
【问题描述】:

在将一些代码从我的测试项目转移到以 Windows CE 为目标的“真实”项目时,一些代码在 IDE 中变得尴尬并变红,即“TryParse()”。

由于缺少……马蹄铁,战斗失败了;希望 TryParse() 的缺失不会导致类似healthcare.gov 的eCatastrophe;然而,有没有比 TryParseless 解析器重写 TryParse() 更好的方法:

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!");
}

?

【问题讨论】:

  • 如果s 是一个字符串,那永远不会成功。事实上,它甚至不会编译,因为编译器可以 100% 确定它永远不会成功。
  • 真;我更改了它,但我的问题还是一样:鉴于 WindowsCE 目标的限制,是否有一种不那么笨拙的方法来实现这一点?

标签: c# casting windows-ce tryparse target-platform


【解决方案1】:

考虑到s 是一个字符串值,您不能将其转换为int。如果 int.TryParse 不可用,那么您可以创建自己的方法,该方法将返回一个 bool 。比如:

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;
        }
    }
}

然后使用它:

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

int.TryParse 内部使用try-catch 进行解析,实现方式类似。

【讨论】:

  • 根据这个问题:stackoverflow.com/questions/15294878/…,我不认为int.TryParse 使用try-catch。如果它不可用,我仍然会这样写。
  • @JoelRondeau,我实际上是在查看源代码,但是是的,它似乎 int.TryParse 不使用异常处理
【解决方案2】:
public bool TryParseInt32( this string str, out int result )
{
    result = default(int);

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

    return true;
}

用法:

int result;
string str = "1234";

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

【讨论】:

    【解决方案3】:

    我假设s 是一个字符串。如果是这样,您的代码将无法正常工作。以下代码应该:

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

    【讨论】:

    • 谢谢;不过,我仍然想知道是否有比笨拙的 try/catch 更好的选择......
    • @ClayShannon - 我不知道:(
    • @ClayShannon 没有......这是显而易见的选择。 Habib 的答案可能包含 tryparse 的实际正文。您可以跟随他的领导并定义自己的函数来实现它,这样您就不会到处都有 try-catch,但是没有办法使用 try-catch。
    【解决方案4】:

    你可以使用正则表达式。

    public bool IsNumber(string text)
    {
        Regex reg = new Regex("^[0-9]+$");
        bool onlyNumbers = reg.IsMatch(text);
        return onlyNumbers;
    }
    

    【讨论】:

    • 有趣的解决方案;谢谢;我把它调高了,但通常当我看到 Regex 时,我会跑到山上,就好像我刚刚在小路中间遇到了一条摇晃的眼镜蛇。
    • 你有问题。它可以用正则表达式解决。现在你有两个问题。
    猜你喜欢
    • 2010-11-08
    • 2010-10-27
    • 2019-10-05
    • 1970-01-01
    • 2023-03-30
    • 2011-01-30
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多