是否可以扩展List <T>但仅适用于T =精确类型?

Ilh*_*han 1 c# extension-methods

我正在尝试扩展类,并设法扩展List<T>以获得乐趣:

public static void SomeCustomSort<T>(this List<T> list, string item)
{
    if (typeof(T) != typeof(string) || list.Count == 0)
        return;

    // doStuff();
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更智能的方法来扩展List<T>,List<string>以便我的扩展方法没有列出或可访问任何其他类型T

Ser*_*kiy 8

只是让你的方法非泛型:

 public static void SomeCustomSort(this List<string> list, string item)
Run Code Online (Sandbox Code Playgroud)

并指定它应该使用的确切类型


注意:使用void方法,即使您想将扩展方法参数限制为某些类型的集合(例如某些接口的所有实现者或某些非密封类以及从中派生的类),我也不建议使用带参数约束的泛型方法:

public static void SomeCustomSort<T>(this List<T> animals)
   where T: IAnimal
Run Code Online (Sandbox Code Playgroud)

为什么?因为它使代码过于复杂.非泛型方法比泛型方法更容易理解.没有约束的通用方法比具有约束的通用方法更容易理解.您应该从易于理解的最简单的解决方案开始.听起来更自然吗?

  • "它列出了动物名单"
  • "它排序任何类型的项目列表"
  • "它列出任何类型的动物物品清单"

何时使用泛型类型约束?从方法返回项目时,您不希望丢失有关列表项的确切类型的信息.考虑通过一些重量过滤器返回动物的方法

public static IEnumerable<IAnimal> WhereWeightBelow(this List<IAnimal> animals, int weight)
Run Code Online (Sandbox Code Playgroud)

如果您将狗列表传递给此方法,您将失去方法输出中所有狗特定信息的智能感知.

dogs.WhereWeightBelow(10).Where(d => d. /* oops only IAnimal members here */)
Run Code Online (Sandbox Code Playgroud)

返回通用类型将保留所有狗信息.


SO *_*ood 5

另一种尚未提及的替代方案:

public static void SomeCustomSort<T>(this List<T> list, string item) 
  where T: YourSpecificType
Run Code Online (Sandbox Code Playgroud)

这允许您指定不止一种类型,例如:

public static void SomeCustomSort<T>(this List<T> list, string item) 
  where T: ISortable, ICustomInterface
Run Code Online (Sandbox Code Playgroud)

  • 另外,我不认为我可以将“string”指定为 YourSpecificType 我错了吗? (4认同)
  • 通用方法受单一不可继承类型限制?支持者,请提供通用方法的优点 (2认同)