Menu
CoddyTech

泛型方法

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

C 没有泛型。可复用的 C 函数使用 void * 参数;如果像 qsort 那样需要遍历数组,还要传入元素大小。调用方需要将结果强制转换回来,因此没有任何机制会检查回退值和元素是否属于同一类型。宏和 C11 的 _Generic 会在编译时根据类型选择代码,但不会为你提供一个类型化函数。在 C# 泛型方法中,T 会将数组元素类型与回退值和结果的类型关联起来,编译器会根据参数推断 T,而且不需要强制转换。

泛型类型参数无需使用对象强制转换,就能关联参数类型和结果类型。类型推断通常会根据参数选择 T。这里显式指定了默认回退值,而不是使用 default(T),因为缺失值的处理方式由调用方控制。此编译器支持泛型方法语法。

C 参考

#include <stdio.h>

static const void *first_or(const void *values, size_t count, const void *fallback) {
    return count == 0 ? fallback : values;
}

int main(void) {
    const char *names[] = {"A", "B"};
    const char *none = "none";
    const char *const *first = first_or(names, 2, &none);
    printf("%s\n", *first);
    return 0;
}

C# 支持性声明

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

Main 中的 C# 语句

Console.WriteLine(FirstOr(new[] { "A", "B" }, "none"));

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

参考输出:

A

C# 输出:

A
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自我测试

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

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

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