views:

68

answers:

2

Is there any way to using reflection in .net to get a property's value using a path like so...

type t {
    id : int
    name : string
}

type s {
    id : int
    st : t
{

let a = {id = 1; {id = 2; name = "foo"}}

a.getType().getProperty("st.name")

Sorry for the F#. This doesn't work obviously but it illustrates what I'm trying to do. I could write a recursive algorithm for this but does anybody know of a mechanism in the API to accomplish this?

A: 

Unfortunately, there is no built-in method to handle this. It would be very difficult and error prone, since there are lots of options here ("st" could be null, a different type at runtime if it's defined as System.Object, etc...).

You'll need to handle this by recursively walking the properties.

Reed Copsey
A: 

You can use DataBinder.Eval to dynamically evaluate path expressions (although this will mean adding a dependency to System.Web):

http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx

C# Example:

using System;
using System.Web.UI;

namespace DataBinderEval
{
    internal class Program
    {
        private static void Main()
        {
            object target = new s { id = 1, st = new t { id = 2, name = "foo" } };

            string expression = "st.name";

            object result = DataBinder.Eval(target, expression);

            Console.WriteLine(result);
        }

        private class t
        {
            public int id { get; set; }
            public string name { get; set; }
        }

        private class s
        {
            public int id { get; set; }
            public t st { get; set; }
        }           
    }
}
chibacity
Unfortunately, I can't use this as I am writing a siverlight app in F#
PhilBrown