((IEnumerable)source).OfType<T>()
和有什么区别source as IEnumerable<T>
对我来说,它们看起来很相似,但事实并非如此!
source
是 type IEnumerable<T>
,但它被装箱为object
.
编辑
这是一些代码:
public class PagedList<T> : List<T>, IPagedList
{
public PagedList(object source, int index, int pageSize, int totalCount)
{
if (source == null)
throw new ArgumentNullException("The source is null!");
// as IEnumerable<T> gives me only null
IEnumerable<T> list = ((IEnumerable)source).OfType<T>();
if (list == null)
throw new ArgumentException(String.Format("The source is not of type {0}, the type is {1}", typeof(T).Name, source.GetType().Name));
PagerInfo = new PagerInfo
{
TotalCount = totalCount,
PageSize = pageSize,
PageIndex = index,
TotalPages = totalCount / pageSize
};
if (PagerInfo.TotalCount % pageSize > 0)
PagerInfo.TotalPages++;
AddRange(list);
}
public PagerInfo PagerInfo { get; set; }
}
在另一个地方,我创建了一个 PagedList 的实例
public static object MapToPagedList<TSource, TDestination>(TSource model, int page, int pageSize, int totalCount) where TSource : IEnumerable
{
var viewModelDestinationType = typeof(TDestination);
var viewModelDestinationGenericType = viewModelDestinationType.GetGenericArguments().FirstOrDefault();
var mappedList = MapAndCreateSubList(model, viewModelDestinationGenericType);
Type listT = typeof(PagedList<>).MakeGenericType(new[] { viewModelDestinationGenericType });
object list = Activator.CreateInstance(listT, new[] { (object) mappedList, page, pageSize, totalCount });
return list;
}
如果有人能告诉我为什么我必须将 mappedList 转换为对象,我将非常感激:)
这里是 MapAndCreateSubList 方法和 Map 委托:
private static List<object> MapAndCreateSubList(IEnumerable model, Type destinationType)
{
return (from object obj in model select Map(obj, obj.GetType(), destinationType)).ToList();
}
public static Func<object, Type, Type, object> Map = (a, b, c) =>
{
throw new InvalidOperationException(
"The Mapping function must be set on the AutoMapperResult class");
};