我正在学习Linkedin Learning的c#,在一节课上,教授的代码在视频中非常有效,但完全相同的文件不适用于我,返回错误:

Input string was not in a correct format.

这是不起作用的代码:

using System; 
using System.Globalization;

namespace Parsing {
    class Program
    {
        static void Main(string[] args)
        {
            string numStr = "2.00";

            int targetNum=0;
            try {

                targetNum = int.Parse(numStr, NumberStyles.Float);
                Console.WriteLine(targetNum);

            }
            catch(Exception e) {
                Console.Write(e.Message);
                
            }
         
            bool succeeded = false;
            
            if (succeeded) {
                Console.WriteLine($"{targetNum}");
            }
        }
    } 
}

然而,这确实有效:

using System; 
using System.Globalization;

namespace Parsing {
    class Program
    {
        static void Main(string[] args)
        {
            string numStr = "2";

            int targetNum=0;
            try {

                targetNum = int.Parse(numStr, NumberStyles.Float);
                Console.WriteLine(targetNum);

            }
            catch(Exception e) {
                Console.Write(e.Message);
                
            }
         
            bool succeeded = false;
            
            if (succeeded) {
                Console.WriteLine($"{targetNum}");
            }
        }
    } 
}

有人能解释为什么其他代码不起作用吗?

推荐答案

你的个人资料显示你在巴西,在巴西,"2.5"是"2.5",而不是"2.5".

如果你用"2,00"来运行你的代码,它应该可以工作.

以下是一个不同文化的例子:

foreach(var two in new []{"2.00", "2,00"})
foreach(var culture in new []{"pt-BR", "en-AU"})
{
    bool ok = int.TryParse(two, System.Globalization.NumberStyles.Float, new System.Globalization.CultureInfo(culture), out var i);
    Console.WriteLine($"For '{culture}' '{two}' is {(ok ? "OK" : "not OK")}");
}

这张照片是:

For 'pt-BR' '2.00' is not OK
For 'en-AU' '2.00' is OK
For 'pt-BR' '2,00' is OK
For 'en-AU' '2,00' is not OK

.net相关问答推荐

从Couchbase删除_txn文档的推荐方法?""

删除数据库项目中的表

Powershell机器令牌组

为什么Regex.Escape支持数字符号和空格?

在数据网格中:如何在更改单元格 A 中的值后显示单元格 B 中的更改

是否有任何为 C# 编写的模糊搜索或字符串相似函数库?

我可以从我的应用程序中抛出哪些内置 .NET 异常?

一种消耗(所有字节)BinaryReader 的优雅方式?

找不到 Microsoft.Office.Interop Visual Studio

RNGCryptoServiceProvider 的优缺点

编译错误:显式实现接口时修饰符 'public' 对此项目无效

获取 .NET Framework 目录路径

实体框架 - 无法将 lambda 表达式转换为类型字符串,因为它不是委托类型

从 Windows 窗体打开 URL

如何正确和完全关闭/重置 TcpClient 连接?

如何在安装后立即启动 .NET Windows 服务?

如何将 MailMessage 对象作为 *.eml 或 *.msg 文件保存到磁盘

WPF中的依赖属性和附加属性有什么区别?

可以从 C# 调用 C++ 代码吗?

枚举和匹配属性的 C# 命名约定