无法将字符串解析为整数值

时间:2014-03-14 05:09:33

标签: c# string integer appsettings

我真的不知道为什么我会得到0的价值:

enter image description here

但是这段代码效果很好:

int val = Convert.ToInt32("1546");    

这是appsetting:

<add key="PesoPayMerchantId" value="​1546"/>

有什么想法吗?

Edit1

我想得到"1546"的整数值,但它无法正常工作 以下是获取appsetting的代码:

    public static string GetConfigurationString(string appSettingValue)
    {
        return ConfigurationManager.AppSettings[appSettingValue];
    }  

我已经尝试了你的建议,结果就是这样:

enter image description here
enter image description here
enter image description here

字符串值是正确的("1546"),但不能解析为整数。这里发生了什么?

修改2

我非常确定:

的价值
<add key="PesoPayMerchantId" value="​1546"/>  

实际上是数字"1546"的组合 但是当我尝试使用Immediate Window重新编写字符串值时,现在可以解析它。但我仍然无法找出这个Bug的原因?

enter image description here

编辑3

最后,由于Johnny

,它现在有效

我所做的是,我重写了整个<add key="PesoPayMerchantId" value="1546"/>,现在可以解析它了。感谢你的帮助。 :d

4 个答案:

答案 0 :(得分:3)

答案是,重新编写配置 我记得,我只是来自pdf文件的copied and paste "1546" 所以吸取教训,不要太懒于输入值。

附加信息:
我还记得,我在paste gmail上复制并(google Chrome),我发现我复制的文字在开头包含hidden characters

答案 1 :(得分:2)

我只能认为你正在经历某种奇怪的全球化/文化特定问题。

鉴于您知道号码的确切格式,您可以尝试Int32.TryParse Method (String, NumberStyles, IFormatProvider, Int32) overload,例如:

int.TryParse(val, NumberStyles.Any, CultureInfo.InvariantCulture, out id);

答案 2 :(得分:1)

我会检查Try.Parse的返回值。

来自文档: http://msdn.microsoft.com/en-us/library/f02979c7(v=vs.110).aspx

      int number;
      bool result = Int32.TryParse(value, out number);
      if (result)
      {
         Console.WriteLine("Converted '{0}' to {1}.", value, number);         
      }
      else
      {
         if (value == null) value = ""; 
         Console.WriteLine("Attempted conversion of '{0}' failed.", value);
      }

答案 3 :(得分:1)

此测试断言总是正确的:

namespace SOWTests
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class PTests
    {
        [TestMethod]
        public void PTest()
        {
            string val = "1546";

            int id;
            int.TryParse(val, out id);

            Assert.AreEqual(1546, id);
        }
    }
}

所以问题不在这部分代码中。它可能会被代码的一些调试/分析部分改变。或者可能是非托管呼叫导致堆栈损坏。

相关问题