命名空间与文件
Coddy 面向 Ruby 开发者的 C# 课程的第 29 课,共 48 课。
Ruby 使用嵌套模块定义命名空间,并通过 :: 读取其中的内容,例如 Display::Text.bracket;C# 使用命名空间和点号,例如 Display.Text.Bracket。在 Ruby 中,require_relative 会在运行时加载另一个文件,并执行一次其中的顶层代码。C# 没有这一步:每个源文件都会编译到同一个程序中,而 using 只会缩短名称。Ruby 模块是一个实时对象,你可以重新打开它或 include 它;C# 命名空间只用于归类类型名称。
编译器会将所有源文件合并到一个程序中。命名空间名称用于组织类型,using 会将名称引入作用域;它不会像导入脚本那样执行文件。public 控制这些类型之间的访问权限。即使存在许多类,也只需要一个 Main。
Ruby 参考
module Display
module Text
def self.bracket(value)
"[" + value + "]"
end
end
end
puts Display::Text.bracket("pen")C# 辅助声明
namespace Display { public static class Text { public static string Bracket(string value) { return "[" + value + "]"; } } }Main 中的 C# 语句
Console.WriteLine(Display.Text.Bracket("pen"));这些是用于讲解重点内容的代码片段。挑战文件包含完整、可执行的包装代码;上面的代码片段展示了相关的声明和语句。
Ruby 输出:
[pen]C# 输出:
[pen]挑战
简单在 Pricing.cs 中实现 Catalog.Pricing.Total。对于非负整数输入,它会返回 unit * quantity。Solve 会调用带命名空间的辅助函数。驱动程序也会直接调用它。
编辑未锁定的 C# 文件。可见的锁定文件 Main.cs 会读取所描述的行,调用 Exercise.Solve,验证输入未被修改,并以一个末尾换行符打印结果。保留已声明的 API。不要添加第二个 Main,也不要输出诊断信息。
锁定的启动程序还会独立检查导出的辅助函数或类 API,而不只是检查 Solve 包装函数。
亲手试试
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 = I(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
if (Catalog.Pricing.Total(7,3) != 21 || Catalog.Pricing.Total(4,0) != 0) throw new Exception("Pricing API");
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine(result);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器