方法、默认值和 params
Coddy 面向 C++ 开发者的 C# 课程的第 23 课,共 48 课。
C++ 默认参数类似于 C# 可选参数,但 initializer_list 或参数包与 C# params 并不是同一种 API。C# 静态方法属于某个类型,而不是自由函数。请明确说明调用形式和检查的元素类型。
静态方法属于某个类型,而不是某个实例。省略参数时,可选参数会提供默认值。params 数组会收集末尾的位置参数,也可以接收一个现有数组。请明确写出结果类型;返回值与打印值是两回事。
C++ 参考
#include <algorithm>
#include <array>
#include <cctype>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;
int total(int factor=2,initializer_list<int> values={}) { int sum=0; for(int n:values) sum+=n; return sum*factor; }
int main() {
cout << total(3,{2,4}) << "\n";
}
C# 辅助声明
static string JoinTags(string prefix = "tags", params string[] tags) { return prefix + ":" + string.Join(",", tags); }Main 中的 C# 语句
Console.WriteLine(JoinTags("names", "A", "B"));这些是用于教学的重点片段。挑战文件包含完整的可执行封装;上面的代码片段展示了相关声明和语句。
参考输出:
18C# 输出:
names:A,B挑战
简单读取一个整数序列和一个因子。实现 Total,提供默认值为 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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器