无法将System.Collections.Generic.List [System.Object]类型的对象强制转换为System.Collections.Generic.IList [ShortCodeList]

时间:2014-07-06 18:06:49

标签: c# generics

BindingProperties返回类型T. linq查询在运行时带来的结果是System.Collections.Generic.IList[ShortCodeList]但是当我尝试使用IList T>键入强制转换它时,它返回:

  

无法投射类型的对象   ' System.Collections.Generic.List`1 [System.Object的]'输入   ' System.Collections.Generic.IList`1 [ModelAccessLayer.Model.ShortCodeList]'

    private IList<T> GetResultSetConvertedToList<T>(IList<T> dataSet, IEnumerable<dynamic> resultSet) where T : class, new()
    {
        IList<T> customResult = (IList<T>)(resultSet.Select(x => BindingProperties(new T(), x)).ToList());
        return customResult;
    }

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

select表达式中的类型dynamic导致整个表达式被视为动态表达式,返回IEnumerable<dynamic>

如果您明确告诉C#使用.Select<dynamic,T>,您可以强制返回类型为T,并且您的代码将按预期工作。

    private IList<T> GetResultSetConvertedToList<T>(IList<T> dataSet, IEnumerable<dynamic> resultSet)
        where T : class, new()
    {
        IList<T> customResult = (IList<T>)(resultSet.Select<dynamic, T>(x => BindingProperties(new T(), x)).ToList());
        return customResult;
    }