Menu
CoddyTech

解析时避免异常

Coddy 面向 Python 开发者的 C# 课程的第 6 课,共 48 课。

Python 的 int 转换通常会对格式错误的文本使用异常。C# 的 TryParse 提供了 bool 加 out 的模式,也会检测有界整数溢出。Python 注解不会强制执行这些转换,C# 声明也不会自动解析字符串。

TryParse 返回 bool,并通过 out 参数写入转换后的值。与 Parse 不同,遇到普通的格式错误文本或溢出时,它不会抛出异常。对于面向机器的格式,请使用显式指定的区域性设置。仅声明类型并不能转换外部文本。

Python 参考

try:
    number = int("17")
    print(number)
except ValueError:
    print("invalid")

Main 中的 C# 语句

int number;
bool ok = int.TryParse("17", out number);
Console.WriteLine(ok ? number.ToString() : "invalid");

这些是用于讲解的重点片段。挑战文件包含完整的可执行包装代码;上面的代码片段展示了相关的声明和语句。

参考输出:

17

C# 输出:

17
challenge icon

挑战

简单

输入是一行文本。解析一个带符号的十进制 int,两侧可以有空格。成功时以文本形式返回它的两倍,否则返回 invalid。成功输入的范围为 -1000000 到 1000000;溢出文本视为无效。

编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所述行,调用 Exercise.Solve,验证输入未被修改,并在末尾输出一个换行符。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。

亲手试试

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = input[0]; string before0=Snapshot(a0);

var result = Exercise.Solve(a0);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Python 开发者的 C#中的所有课

自己练习: C# 在线编译器