ebb
ebb

Reputation: 9377

F# - Reflection, Pattern matching: GetValue

| P.Call(_, mi, [P.Value(value, _); P.PropertyGet(q, propInfo, [])]) -> ...

How would I use the GetValue method, in order to get the value for propInfo?

EDIT

Based on @Stephen Swensen' suggestion, I've tried to do:

| 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"

However, it simply throws an exception:

TargetException was unhandled: Object does not match target type.

The value of pi2 at runtime is: Some({PropertyGet (None, Author r, [])})

EDIT

Bahh... didnt notice that pi2 is static.

The solution is:

| 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"

Upvotes: 1

Views: 474

Answers (1)

Stephen Swensen
Stephen Swensen

Reputation: 22297

It depends what kind of property it is (static or instance) and whether or not it takes any arguments.

Based on your pattern match it looks like your property doesn't take any arguments, so we'll put that aside.

If it is a static property, then q is None and you just need to call propInfo.GetValue(null, null).

If it is an instance property, then q is Some(instance) where instance is type Expr. That presents a problem. You need to be able to convert the expression to value you can pass as the first argument to GetValue. But if the expression is arbitrarily complex, that would require a lot of work to implement an expression evaluator.

Upvotes: 2

Related Questions