在 C# 中将简单数字字符串转换为 Int 时引发格式异常

Format Exception Raises When Converting Simple Numeric String to Int in C#

我在 VS2015 中转换字符串时出现奇怪的错误。当我使用 x 变量时,我没有收到任何错误。仅当我使用日期变量时才会引发异常。知道为什么吗???

谢谢

代码:

using System;
using System.Globalization;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string x = "9-1-2015";
            string date = "‎9‎-‎1-‎2015";
            List<string> dt = date.Split('-').ToList();
            List<int> lis = new List<int>();
            foreach (var item in dt)
            {
                lis.Add(int.Parse(item));
            }
        }
    }
}

在您的代码中,下一行有一些隐藏的空格:

string date = "‎9‎-‎1-‎2015";

尝试使用键盘箭头在此行上移动光标,您就会明白我的意思了。

尝试删除此行并手动重写此行的代码(无需复制粘贴),它会起作用

作为乔恩·斯基特

Your date variable value contains non-printable characters, copy and paste your string into http://csharpindepth.com/Articles/General/Unicode.aspx#explorer

因此您必须更改它的生成方式,或者,如果不是 possible/desired,请在将它们解析为 DateTime(这正是您真正想要的)之前将其删除。

您可以使用这种方法:

var unicodeCategories = new[] { UnicodeCategory.DecimalDigitNumber, UnicodeCategory.DashPunctuation };
string cleanDate = string.Concat(date.Where(c => unicodeCategories.Contains(char.GetUnicodeCategory(c))));

现在您可以使用 DateTime.TryParseExact:

DateTime dt;
if (DateTime.TryParseExact(cleanDate, "d-M-yyyy", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt))
    Console.WriteLine("Year:{0} Month:{1} Day:{2}", dt.Year, dt.Month, dt.Day);
else
    Console.WriteLine("Could not be parsed to DateTime");

用你的date输出:Year:2015 Month:1 Day:9

谢谢蒂姆施梅尔特。

是的,我确实需要清理我的字符串变量。您的代码非常有用,但不适用于我的代码。所以我将代码修改为以下代码。然后我可以将 cleanDate var 解析为 DateTime 对象。

    string date = "9/28/2015 12:00:00 AM"; // In My Code, This Var Contain Unseen Unicode Char.
    var cleanDate = new string(date.Where(c => char.IsNumber(c) || char.IsPunctuation(c) || char.IsWhiteSpace(c) || char.IsLetter(c)).ToArray());
    DateTime date = DateTime.ParseExact(cleanDate, "M/d/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);