p.s*_*w.g 6 .net c# linq generics casting
所以我有一个接受泛型类型参数的类,如果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;
}
Run Code Online (Sandbox Code Playgroud)
但是我在最后一行得到例外
Cannot convert type 'MySpecialModel' to 'T'
Run Code Online (Sandbox Code Playgroud)
如果我更改代码as而不是强制转换,我会收到此错误.
The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
更新
这个类需要可以采用任何类型参数,包括structs和内置类型,因此在我的情况下,通用约束不是一个合适的解决方案.
做Select(x => (MySpecialModel)x)
LINQCast<T>方法仅适用于将元素转换为该元素已有的状态(例如基本类型、派生类型或接口)。它并不旨在将能够转换为目标类型的对象转换。(例如new List<int>{1,2,3}.Cast<long>()也会抛出异常。
上面的答案没有错,但没有解决问题。
仅仅因为您通过反射证明了泛型参数绑定到给定类型,并不意味着编译器知道它是绑定的。为了使其工作,您需要将T实例转换为通用类型(例如object),然后将其转换为特定类型。例如(将查询中的最后一行更改为select (T)(object)m应该可以解决问题。