在确保T实际上是整数之后,我试图将泛型类型参数T值的值转换为整数:
public class Test
{
void DoSomething<T>(T value)
{
var type = typeof(T);
if (type == typeof(int))
{
int x = (int)value; // Error 167 Cannot convert type 'T' to 'int'
int y = (int)(object)value; // works though boxing and unboxing
}
}
}
Run Code Online (Sandbox Code Playgroud)
虽然它通过装箱和拆箱工作,但这是一个额外的性能开销,如果有办法直接进行,我就会徘徊.
在通过Reflector 查看System.Linq.Enumerable时,我注意到用于Select和Where扩展方法的默认迭代器- WhereSelectArrayIterator - 没有实现ICollection接口.如果我正确读取代码,这会导致一些其他扩展方法,如Count()和ToList()执行较慢:
public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
{
// code above snipped
if (source is List<TSource>)
{
return new WhereSelectListIterator<TSource, TResult>((List<TSource>) source, null, selector);
}
// code below snipped
}
private class WhereSelectListIterator<TSource, TResult> : Enumerable.Iterator<TResult>
{
// Fields
private List<TSource> source; // class has access to List source so can implement ICollection
// code below snipped
}
public class …Run Code Online (Sandbox Code Playgroud)