3

我想通过例子来理解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
        */

我们可以说 TSource 是“pet”,key 是“Age”,pet => pet.Age 是

 Func<TSource, TKey>?

谢谢。

4

3 回答 3

10

不,TSource是类型PetTKey是类型int。因此,不使用类型推断,您将拥有:

IEnumerable<Pet> query = pets.OrderBy<Pet, int>(pet => pet.Age);

TSource并且TKey是方法的泛型类型参数。您可以将它们视为类的泛型类型参数......所以在List<T>,T是类型参数,如果你写:

List<string> names = new List<string>();

那么这里的类型参数string(所以你可以说T=string在这种情况下,以手动方式)。

您的情况的不同之处在于编译器根据方法调用参数为您推断类型参数。

于 2012-08-17T20:35:51.937 回答
1

不,来自msdnEnumerable.OrderBy<TSource, TKey> Method (IEnumerable<TSource>, Func<TSource, TKey>

  • TSource

    源元素的类型。

  • 密钥

    keySelector 返回的键的类型。参数源类型:System.Collections.Generic.IEnumerable

    要排序的一系列值。keySelector 类型:System.Func

    从元素中提取键的函数。

所以TSource= Pet; TKey=int

于 2012-08-17T20:40:56.210 回答
1

Jon Skeet 的相当彻底地涵盖了这些细节。话虽如此,在这种情况下,通过使用 Visual Studio 中的鼠标浮动工具来查看 Generic 的播放方式是很有用的。

在此处输入图像描述

于 2012-08-17T20:50:26.197 回答