小编Ale*_*man的帖子

如何将Generic Type Argument的值转换为具体类型?

在确保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)

虽然它通过装箱和拆箱工作,但这是一个额外的性能开销,如果有办法直接进行,我就会徘徊.

.net c# generics

11
推荐指数
1
解决办法
6735
查看次数

为什么WhereSelectArrayIterator没有实现ICollection?

在通过Reflector 查看System.Linq.Enumerable时,我注意到用于SelectWhere扩展方法的默认迭代器- 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)

c# performance list icollection toarray

1
推荐指数
1
解决办法
1445
查看次数

标签 统计

c# ×2

.net ×1

generics ×1

icollection ×1

list ×1

performance ×1

toarray ×1