我正在尝试弄清楚从调用返回的obj是否是某种类型。下面是我的代码:
type MyType<'T>=
val mutable myArr : array
val mutable id : int
val mutable value : 'T在某些具有MyType作用域的方法中...
let a = someFunThatReturnsObj() // a could be of type MyType 如何判断a是否为MyType类型?
发布于 2010-10-20 03:44:56
match a with
| :? MyType<int> as mt -> // it's a MyType<int>, use 'mt'
| _ -> // it's not如果您只关心某个未知X的MyType<X>,那么
let t = a.GetType()
if t.IsGenericType && t.GetGenericTypeDefinition() = typedefof<MyType<int>> then
// it is发布于 2010-10-21 02:13:00
我不认为这是那么简单(记住我是f#幼稚的)考虑下面的场景
1)我们在多个类型上使用泛型2)我们没有对象的类型信息,因此它作为类型obj进入函数,就像在一些.NET数据契约/序列化库中一样
我修改了我的建议,使用反射:
type SomeType<'A> = {
item : 'A
}
type AnotherType<'A> = {
someList : 'A list
}
let test() =
let getIt() : obj =
let results : SomeType<AnotherType<int>> = { item = { someList = [1;2;3] }}
upcast results
let doSomething (results : obj) =
let resultsType = results.GetType()
if resultsType.GetGenericTypeDefinition() = typedefof<SomeType<_>> then
let method = resultsType.GetMethod("get_item")
if method <> null then
let arr = method.Invoke(results, [||])
if arr.GetType().GetGenericTypeDefinition() = typedefof<AnotherType<_>> then
printfn "match"
getIt() |> doSomething 似乎应该有更自然的方式来做这件事...
https://stackoverflow.com/questions/3972043
复制相似问题