我正在学习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相关问答推荐

无法在 Blazor Server 应用程序中触发 InputRadio 的 onchange 事件

信号量的多线程问题

如何规范机器之间连字符的排序顺序?

类似于字典但没有值的 C# 数据 struct

如何将 Javascript 日期时间转换为 C# 日期时间?

maxRequestLength 的最大值?

在 web api 控制器(.net 核心)中使用 async/await 或任务

如何在 C# 中创建表达式树来表示String.Contains("term")?

在 WinForms 应用程序中查找焦点控件的首选方法是什么?

为什么递归调用会导致不同堆栈深度的 StackOverflow?

什么是 project.lock.json?

Java 和 .NET 技术/框架的类似物

哪个更快:清除集合或实例化新的

Dapper 是否支持 SQL 2008 表值参数?

非通用 TaskCompletionSource 或替代

自定义属性的构造函数何时运行?

mscorlib 代表什么?

MemoryCache 不遵守配置中的内存限制

C# - 在 WPF 应用程序中保存用户设置的方法?

泛型类的静态成员是否与特定实例相关联?