我想通过这个例子来理解TSource的概念,Tkey.
我们有代码
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
public static void OrderByEx1()
{
Pet[] pets = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
IEnumerable<Pet> query = pets.OrderBy(pet => pet.Age);
foreach (Pet pet in query)
{
Console.WriteLine("{0} - {1}", pet.Name, pet.Age);
}
}
/*
This code produces the following output:
Whiskers - 1
Boots - 4
Barley - 8
*/
Run Code Online (Sandbox Code Playgroud)
我们可以说TSource是"宠物",关键是"年龄"和宠物=> pet.Age是
Func<TSource, TKey>?
Run Code Online (Sandbox Code Playgroud)
谢谢.
Jon*_*eet 10
不,TSource是类型Pet,TKey是类型int.所以不使用类型推断,你有:
IEnumerable<Pet> query = pets.OrderBy<Pet, int>(pet => pet.Age);
Run Code Online (Sandbox Code Playgroud)
TSource并且TKey是该方法的泛型类型参数.您可以将它们视为类的泛型类型参数...因此List<T>,T是类型参数,如果您编写:
List<string> names = new List<string>();
Run Code Online (Sandbox Code Playgroud)
那么这里的类型参数是string(所以你可以说,T=string在这种情况下,以手工波浪的方式).
您的情况的不同之处在于编译器根据方法调用参数推断出类型参数.