Menu
CoddyTech

命名空间与文件

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

Go 函数位于包中,导出的名称以大写字母开头。C# 方法位于类型中,并使用显式访问修饰符;using 导入的是命名空间,而不是编译引用的文件。这些任务中的同级 .cs 文件会组成一个程序集。

编译器会将所有源文件合并为一个程序。命名空间名称用于组织类型,using 会将名称引入作用域;它不像导入脚本那样执行文件。Public 控制这些类型之间的访问权限。即使有多个类,也只需要一个 Main。

Go 参考

package main
import ("fmt")
func total(price,count int)int{return price*count}
func main() {
fmt.Println(total(3,4))
}

C# 辅助声明

namespace Display { public static class Text { public static string Bracket(string value) { return "[" + value + "]"; } } }

Main 中的 C# 语句

Console.WriteLine(Display.Text.Bracket("pen"));

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

参考输出:

12

C# 输出:

[pen]
challenge icon

挑战

简单

在 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);
}
}
quiz icon自我测试

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

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

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