match value with
| :? list<#SomeType> as l -> l //Is it possible to match any list of a type derived from SomeType?
| _ -> failwith "doesn't match"
正如已经指出的,没有办法直接做到这一点(模式匹配只能绑定值,但不能绑定新类型变量)。除了(更一般的)解决方法之外kvb您可以利用所有集合都实现非泛型的事实IEnumerable
,所以你可以检查这种类型:
match box value with
| :? System.Collections.IEnumerable as l when
// assumes that the actual type of 'l' is 'List<T>' or some other type
// with single generic type parameter (this is not fully correct, because
// it could be other type too, but we can ignore this for now)
typedefof<SomeType>.IsAssignableFrom
(value.GetType().GetGenericArguments().[0]) ->
l |> Seq.cast<SomeType>
| _ -> failwith "doesn't match"
该代码测试该值是否是非泛型IEnumerable
以及类型参数是否是子类型SomeType
。在这种情况下,我们得到了一些派生类型的列表,因此我们可以将其转换为一系列SomeType
值(这与使用派生类型的值列表略有不同,但对于实际目的来说应该不重要)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)