开发者

Reflection using path strings in .NET

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?


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; }
        }           
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜