Menu
CoddyTech

泛型方法

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

GDScript 没有泛型函数:适用于任何元素类型的辅助函数会接收一个未指定类型的 Array,并返回 Variant,因此结果会失去静态类型。C# 泛型方法会保留这种输入与输出之间的类型关系,并在编译时强制执行。GDScript 会将空 Array 视为 false,但 C# 要求使用 Length == 0 来判断,而不会将数组视为 bool。

泛型类型参数可以关联参数类型和结果类型,而无需使用 object 强制转换。类型推断通常会根据参数选择 T。这里明确提供了默认回退值,而不是使用 default(T),因为调用方可以控制缺少值时的处理方式。此编译器支持泛型方法语法。

GDScript 参考

extends Node

func first_or(values: Array, fallback: Variant) -> Variant:
	return values[0] if values else fallback

func _ready():
	print(first_or(["A", "B"], "none"))

C# 辅助声明

static T Echo<T>(T value) { return value; }

Main 中的 C# 语句

Console.WriteLine(Echo("A"));

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

参考输出:

A

C# 输出:

A
challenge icon

挑战

简单

为数组实现 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);
}
}
quiz icon自我测试

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

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

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