您可以创建一个扩展方法,该方法将在运行时返回正确的类型:
public static class LinqExtensions
{
public static Type GetElementType(this IEnumerable source)
{
var enumerableType = source.GetType();
if (enumerableType.IsArray)
{
return enumerableType.GetElementType();
}
if (enumerableType.IsGenericType)
{
return enumerableType.GetGenericArguments().First();
}
return null;
}
}
更新:我添加了用于IEnumerable<T>
对非泛型执行泛型特定排序的机制IEnumerable
public static class SortingExtensions
{
public static IEnumerable<T> CustomSort<T>(this IEnumerable<T> source, string sortProperties)
{
// sort here
}
public static IEnumerable CustomSort(this IEnumerable source, string sortProperties)
{
var elementType = source.GetElementType();
var genericElementType = typeof (IEnumerable<>).MakeGenericType(elementType);
var sortMethod = typeof (SortingExtensions).GetMethod(
"CustomSort",
BindingFlags.Public | BindingFlags.Static,
null,
new [] {genericElementType, typeof (string)},
null);
return (IEnumerable) sortMethod.Invoke(null, new object[] {source, sortProperties});
}
}