我正在尝试扩展类并设法扩展 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
最佳答案
只需使您的方法非泛型:
public static void SomeCustomSort(this List<string> list, string item)
并指定它应该使用的确切类型
注意:使用 void 方法,即使您想将扩展方法参数限制为某些类型集(例如,某些接口(interface)的所有实现者或某些非密封类以及派生自它的类),我也不建议使用带有参数的泛型方法约束:
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 */)
返回通用类型将为您保留所有狗的信息。
关于c# - 是否可以扩展 List<T> 但仅限于 T = 精确类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41397959/