加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在linq查询中转换泛型类型

发布时间:2020-12-15 08:16:37 所属栏目:百科 来源:网络整理
导读:所以我有一个接受泛型类型参数的类,如果type参数是给定类型的子类,则会进行一些特殊处理. IEnumerableT models = ...// Special handling of MySpecialModelif (filterString != null typeof(MySpecialModel).IsAssignableFrom(typeof(T))){ var filters = f
所以我有一个接受泛型类型参数的类,如果type参数是给定类型的子类,则会进行一些特殊处理.
IEnumerable<T> models = ...

// Special handling of MySpecialModel
if (filterString != null && typeof(MySpecialModel).IsAssignableFrom(typeof(T)))
{
    var filters = filterString.Split(...);
    models = 
        from m in models.Cast<MySpecialModel>()
        where (from t in m.Tags
               from f in filters 
               where t.IndexOf(f,StringComparison.CurrentCultureIgnoreCase) >= 0
               select t)
              .Any()
        select (T)m;
}

但是我在最后一行得到例外

Cannot convert type 'MySpecialModel' to 'T'

如果我更改代码而不是强制转换,我会收到此错误.

The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.

我在这里错过了什么?

更新

这个类需要可以采用任何类型参数,包括结构和内置类型,因此在我的情况下,通用约束不是一个合适的解决方案.

解决方法

选择(x =>(MySpecialModel)x)

LINQ Cast< T> method仅适用于将元素转换为元素已经存在的元素(例如基类型,派生类型或接口).它不打算转换能够转换为目标类型的对象. (例如,新的List< int> {1,2,3} .Cast< long>()也会抛出异常.

上面的答案没有错,但它没有解决这个问题.

仅仅因为你已经通过反射证明泛型参数绑定到给定类型,并不意味着编译器知道它是.为了使其工作,您需要将T实例转换为公共类型(例如对象),然后将其转换为特定类型.例如(将查询中的最后一行更改为选择(T)(对象)m应该可以解决问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读