【发布时间】:2010-09-17 21:51:15
【问题描述】:
((IEnumerable)source).OfType<T>()和source as IEnumerable<T>有什么区别
对我来说,它们看起来很相似,但实际上并不相似!
source 的类型为 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");
};
【问题讨论】:
-
这是一个测验问题吗?你似乎遗漏了一些信息。无论如何,OfType
只过滤掉该类型的可枚举元素,所以这是最大的区别。 -
我在我的代码源中使用了 IEnumerable
并证明它不为空,但它为空。我查看了调试器,发现 T 是正确的。然后我使用 ((IEnumerable)source).OfType () 并且转换是正确的,没有空结果。如果你愿意,我可以发布更多代码。
标签: c# linq casting ienumerable boxing