所以我有一個接受泛型類型參數的類,如果類型參數是給定類型的子類,則會進行一些特殊處理。在LINQ查詢中鑄造泛型類型
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;
}
但如果我改變使用as
而不是鑄造的代碼我得到的最後一行
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.
我在這裏錯過了什麼?
更新
此類需求可以採取任何類型的參數,包括struct
S和內置的類型,所以通用約束就不會在我的情況下,合適的解決方案。
你是否在泛型類中設置了約束'where T:class'? – 2013-03-11 21:53:58
@danradu不,但這不適用於我的情況,因爲泛型類可以接受參考和值類型參數。 – 2013-03-11 21:57:32
@ p.s.w.g,參見更新 – smartcaveman 2013-03-11 21:57:54