泛型方法
Coddy 面向 Kotlin 开发者的 C# 课程的第 24 课,共 48 课。
Kotlin 会将泛型类型参数声明在函数名之前,而 C# 会将它放在方法名之后。两者都用于关联输入类型和输出类型。Kotlin 的声明处变型和 reified 内联类型参数是独立的特性,不能从这个简单的 C# 泛型方法中推断出来。
泛型类型参数可以关联参数类型和结果类型,而无需使用 object 强制转换。类型推断通常会根据参数选择 T。这里显式指定了默认回退值,而不是使用 default(T),因为调用方可以控制缺失值的处理策略。此编译器支持泛型方法语法。
Kotlin 参考
fun <T> firstOr(values:List<T>,fallback:T):T=if(values.isEmpty())fallback else values[0]
fun main() {
println(firstOr(listOf("A","B"),"none"))
}C# 辅助声明
static T Echo<T>(T value) { return value; }Main 中的 C# 语句
Console.WriteLine(Echo("A"));这些是用于教学的重点片段。挑战文件中包含完整的可执行包装代码;上面的代码片段展示了相关声明和语句。
参考输出:
AC# 输出:
A挑战
简单为数组实现 FirstOr<T>。如果数组为空,则返回第一个元素或 fallback。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);
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 C#中的所有课
1从这里开始
运行你的第一个 C# 程序自己练习: C# 在线编译器