使用'flexible'类型参数对泛型类型进行模式匹配

Dan*_*iel 6 f# pattern-matching

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"
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 8

正如已经指出的那样,没有办法直接这样做(模式匹配只能绑定值,但它不能绑定新的类型变量).除了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"
Run Code Online (Sandbox Code Playgroud)

该代码测试该值是否为非泛型值IEnumerable以及type参数是否为子类型SomeType.在这种情况下,我们得到了一些派生类型的列表,因此我们可以将它转换为一系列SomeType值(这与使用派生类型的值列表略有不同,但实际上并不重要).


kvb*_*kvb 3

不,不幸的是不可能做这样的事情 - CLR 没有提供任何有效的方法来进行此类类型测试。请参阅如何将对象转换为 F#和F#中的泛型类型列表,以及如何在非泛型方法中对泛型进行模式匹配,以实现一些(相当丑陋)解决方案的接口。