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"
6
A
回答
3
不,不幸的是不可能做到這樣的事情--CLR不提供任何有效的方法來做這種類型的測試。請參閱How to cast an object to a list of generic type in F#和F# and pattern matching on generics in a non-generic method implementing an interface瞭解一些(相當難看的)解決方案。
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"
的代碼測試是否是非泛型IEnumerable
以及類型參數是否爲SomeType
的子類型。在這種情況下,我們得到了一些派生類型的列表,所以我們可以將其轉換爲SomeType
值的序列(這與使用派生類型的值列表稍有不同,但對於實際目的應該沒有關係) 。
2
我以後需要一些類似的匹配懶惰實例。這是我的解決方案,以防有人發現它有幫助。
let (|Lazy|_|) (value : obj) =
if box value <> null then
let typ = value.GetType()
if typ.IsGenericType && typ.GetGenericTypeDefinition() = typedefof<Lazy<_>> then
Some(typ.GetGenericArguments().[0])
else None
else None
用法:
match value with
| Lazy typ when typeof<SomeType>.IsAssignableFrom(typ) -> (value :?> Lazy<_>).Value
| _ -> failwith "not an instance of Lazy<#SomeType>"
0
按照F# 2.0 specification,不相上下。 14.5.2(解決子類型約束),它不起作用,因爲:「F#泛型類型不支持協變或逆變。」
1
不乾淨的,但有效:
let matchType<'T>() =
try
let o = Activator.CreateInstance<'T>()
match box o with
| :? Type1 -> printfn "Type1"
| :? Type2 -> printfn "Type2"
| _ -> failwith "unknown type"
with
| ex -> failwith "%s" (ex.ToString())
相關問題
- 1. 模式匹配和(ereased)泛型函數類型參數
- 2. 如何模式匹配泛型類型參數?
- 3. 泛型類型和類型不匹配
- 4. 泛型 - 使用GetRuntimeMethod與類型參數
- 5. 泛型類型不匹配
- 6. Scala類型與泛型不匹配
- 7. 方法與泛型參數之間的不匹配類型
- 8. 類泛型的類型不匹配
- 9. 使用泛型類型參數類
- 10. Scala的模式匹配類型爲Class的類型參數
- 11. C#泛型:更好的方式來匹配泛型的類型?
- 12. 類型參數的類型不匹配
- 13. 在參數匹配指定泛型類類型
- 14. 模式與給定下面的類模式匹配泛型
- 15. 模式與case類與類型參數不工作匹配
- 16. 類型參數E隱藏類型E.類的泛型模板
- 17. 泛型類型參數不是類型?
- 18. 泛型類型參數和類型
- 19. 模式匹配類型同義詞/類型內部類型參數同義詞
- 20. 泛型類型參數通配符
- 21. 帶泛型類型參數的網絡泛型類型
- 22. 匹配Scala宏中的泛型類型
- 23. unmarshall類與泛型參數
- 24. 模式與類型參數匹配一定到最終類
- 25. 與類型的動態計數泛型類型參數
- 26. Java泛型類型參數
- 27. 泛型類型參數
- 28. 泛型模板非類型參數
- 29. Ninject.Extensions.Factory與非泛型類型參數
- 30. 與Java泛型類型參數
不,我想這是重要的,但爲什麼你需要匹配某種類型的列表?如果列表是同質的,那麼你可以簡單地按列表處理列表元素,這很好。如果列表是異構的,那麼無論如何您都不能將列表視爲邏輯單元。你想在這裏解決什麼問題? – 2010-09-22 01:08:42
我想我應該使用我的實際代碼。爲了簡單起見,我只是使用列表。問題是如何對類型參數進行靈活的匹配。 –
Daniel
2010-09-22 03:27:59