2011-06-14 96 views
1
| P.Call(_, mi, [P.Value(value, _); P.PropertyGet(q, propInfo, [])]) -> ... 

我將如何使用GetValue方法,以獲取propInfo價值?F# - 反射,模式匹配:的GetValue

編輯

基於@Stephen斯文森」的建議,我試圖做的事:

| P.Call(_, mi, [P.Value(value, _); P.PropertyGet(q, pi, [])]) -> 
    match q.Value with 
    | P.PropertyGet(_, pi2, []) -> printfn "%A" <| pi.GetValue(pi2, null) 
    | _ -> failwith "fail" 

然而,它只是拋出一個異常:

TargetException了未處理:對象 與目標類型不匹配。

pi2在運行時的值是:Some({PropertyGet (None, Author r, [])})

編輯

Bahh ......沒有注意到這pi2是靜態的。

解決的辦法是:

| P.Call(_, mi, [P.Value(value, _); P.PropertyGet(q, pi, [])]) -> 
    match q.Value with 
    | P.PropertyGet(_, pi2, []) -> 
     let getObj = pi2.GetValue(null, null) 
     printfn "%A" <| pi.GetValue(getObj, null) 
    | _ -> failwith "fail" 

回答

2

這要看是什麼樣的性質是(靜態或實例),以及是否需要任何參數。

根據你的模式匹配,它看起來像你的財產沒有任何參數,所以我們把它放在一邊。

如果它是一個靜態屬性,那麼qNone,你只需要撥打propInfo.GetValue(null, null)

如果它是實例屬性,則qSome(instance),其中instanceExpr類型。這提出了一個問題。您需要能夠將表​​達式轉換爲您可以作爲第一個參數傳遞給GetValue的值。但是,如果表達式任意複雜,則需要大量工作來實現表達式計算器。

+0

這是一個實例屬性。通過執行'propInfo.GetValue(instance,null)'它會拋出一個異常:TargetException是未處理的:Object與目標類型不匹配。有什麼建議麼? - 只是一個小小的說明,我傳遞了一個「列表」,不知道這是否有所作爲。 – ebb 2011-06-14 20:05:05

+0

@ebb:對,我領先於自己,在意識到'instance'是代表實例的Expr'而不是實例本身的值之後,我更新了我的答案。 – 2011-06-14 20:07:58

+0

@ebb:我不確定你的意思是「傳入一個列表」。 – 2011-06-14 20:13:06