LINQ .Cast() extension method fails but (type)object works

前端 未结 3 1975
南笙
南笙 2020-12-14 18:42

To convert between some LINQ to SQL objects and DTOs we have created explicit cast operators on the DTOs. That way we can do the following:

DTOType MyDTO =          


        
3条回答
  •  有刺的猬
    2020-12-14 19:10

    If you decompile the Linq assembly you get code resembling the following. The previous answer is correct, ultimately the cast is from 'object' to target-type which will always fail for custom types.

    private static IEnumerable CastIterator( IEnumerable source )
    {
        foreach(object current in source)
        {
            yield return (TResult)( (object)current );
        }
        yield break;
    }
    
    public static IEnumerable DCast( this IEnumerable source )
    {
        IEnumerable enumerable = source as IEnumerable;
        if(enumerable != null)
        {
            return enumerable;
        }
        if(source == null)
        {
            throw new ArgumentNullException( "source" );
        }
        return CastIterator( source );
    }
    

    TFish

提交回复
热议问题