Menu
CoddyTech

方法、默认值和 params

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

Python 的 *args 对应 C# 的 params 数组。C# 可选参数受声明类型的限制,并不意味着可以像 Python 那样不受限制地混合参数。C# 静态辅助方法属于某个类型,而 Python 模块函数不需要定义在类中。

静态方法属于某个类型,而不是某个实例。省略参数时,可选参数会使用默认值。params 数组会收集末尾的位置参数,也可以接收现有数组。请明确指定结果类型;返回值和打印值是两回事。

Python 参考代码

def total(factor=2, *values):
    return sum(values) * factor
print(total(3, 2, 4))

C# 辅助声明

static string JoinTags(string prefix = "tags", params string[] tags) { return prefix + ":" + string.Join(",", tags); }

Main 中的 C# 语句

Console.WriteLine(JoinTags("names", "A", "B"));

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

参考输出:

18

C# 输出:

names:A,B
challenge icon

挑战

简单

读取一个整数序列和一个因子。实现 Total,factor 是可选参数,默认值为 2,并接受一个 params 整数数组;Solve 调用它,并返回总和乘以因子的结果。锁定的主程序还会使用默认值和单独的参数调用 Total。

编辑未锁定的 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 = Ints(input[0]); string before0=Snapshot(a0);
var a1 = I(input[1]); string before1=Snapshot(a1);
if (Exercise.Total() != 0 || Exercise.Total(2, 3, 4) != 14) throw new Exception("Total 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自我测试

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

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

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