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

时间:2016-12-30 14:37:38

标签: 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();
}

我想知道是否有一种更智能的方法可以仅为List<T>扩展List<string>,这样我的扩展方法就无法列出,也无法访问任何其他类型T

5 个答案:

答案 0 :(得分:8)

只是让你的方法非泛型:

 public static void SomeCustomSort(this List<string> list, string item)

并指定它应与

配合使用的确切类型

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

public static void SomeCustomSort<T>(this List<T> animals)
   where T: IAnimal

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

  • “它列出了动物名单”
  • “它排序任何类型的项目列表”
  • “它对任何类型的动物”
  • 进行排序

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

public static IEnumerable<IAnimal> WhereWeightBelow(this List<IAnimal> animals, int weight)

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

dogs.WhereWeightBelow(10).Where(d => d. /* oops only IAnimal members here */)

返回通用类型将为您保留所有狗信息。

答案 1 :(得分:4)

只需指定T,而不是将其作为通用方法。

public static void SomeCustomSort(this List<string> list, string item)

答案 2 :(得分:4)

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

s

这允许您指定多于一种类型,例如:

public static void SomeCustomSort<T>(this List<T> list, string item) 
  where T: YourSpecificType

答案 3 :(得分:3)

只需在扩展方法

上准确定义字符串类型即可
public static void SomeCustomSort(this List<string> list, string item)
{   

    // doStuff();
}

答案 4 :(得分:1)

您也可以使用这样的约束(在此示例中,T必须是Project类型):

public static void SomeCustomSort<T>(this List<T> list, string item)
        where T : Project    
    {    
    }
相关问题