Menu
CoddyTech

泛型方法

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

Ruby 方法采用鸭子类型:last_or 接受任意数组和任意备用值,即使是整数数组搭配字符串备用值也可以。RBS 或 Sorbet 可以描述类型参数,但只有外部检查器会强制执行类型约束。C# 泛型方法会将 T 纳入签名,因此编译器会根据参数推断 T,并拒绝 LastOr(new[] { 1, 2 }, "none")。C# 还会检查 Length == 0,而 Ruby 使用 empty?。

泛型类型参数可以关联参数类型和结果类型,而不使用对象强制转换。类型推断通常会根据参数选择 T。这里明确指定了备用值,而不是使用 default(T),因为缺少值时的处理方式由调用方决定。此编译器支持泛型方法语法。

Ruby 参考

def last_or(values, fallback)
  values.empty? ? fallback : values.last
end
puts last_or(["A", "B"], "none")
puts last_or([], "none")
puts last_or([1, 2], "none")

C# 辅助声明

static T LastOr<T>(T[] values, T fallback) { return values.Length == 0 ? fallback : values[values.Length - 1]; }

Main 中的 C# 语句

Console.WriteLine(LastOr(new[] { "A", "B" }, "none"));
Console.WriteLine(LastOr(new string[0], "none"));
Console.WriteLine(LastOr(new[] { 1, 2 }, 0));

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

Ruby 输出:

B
none
2

C# 输出:

B
none
2
challenge icon

挑战

简单

为数组实现 FirstOr<T>。如果数组为空,则返回第一个元素或备用值。Solve 使用整数;锁定的驱动程序还会使用字符串来测试泛型 API。

编辑未锁定的 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.FirstOr(new string[0], "none") != "none" || Exercise.FirstOr(new[]{""}, "fallback") != "") throw new Exception("Generic 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自我测试

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

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

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