解析字段/属性路径?

时间:2014-04-20 11:04:44

标签: c# parsing reflection propertyinfo fieldinfo

所以我编写了这个代码,它可以解析start对象的属性路径,返回有用的属性,并为需要调用返回属性的source对象获取一个out参数。 :

    public static PropertyInfo GetProperty(string path, object start, out object source)
    {
        if (string.IsNullOrEmpty(path))
            throw new ArgumentException();

        source = start;
        var pType = source.GetType();
        var paths = path.Split('.');

        PropertyInfo pInfo = null;
        for (int i = 0; i < paths.Length; i++) {
            var subpath = paths[i];
            pInfo = pType.GetProperty(subpath);
            if (i < paths.Length - 1) { // wonder if there's a better way writing this to avoid this if?
                source = pInfo.GetValue(source);
                pType = source.GetType();
            }
        }
        return pInfo;
    }

现在让我说我有以下层次结构:

    public class Object
    {
        public string Name { get; set; }
    }
    public class GameObject : Object { }
    public class Component : Object
    {
        public GameObject gameObject { get; set; }
    }
    public class MonoBehaviour : Component { }
    public class Player : MonoBehaviour { }
    public class GameManager : MonoBehaviour
    {
        public Player player { get; set; }
    }

样本用法:

        var game = new GameManager
        {
            player = new Player { gameObject = new GameObject { Name = "Stu"} }
        };

        // somewhere else...
        object source;
        var name = GetProperty("player.gameObject.Name", game, out source);
        var value = name.GetValue(source); // returns "Stu"

我的问题是:这仅适用于属性,如何使其适用于属性和字段? - 问题是MemberInfoFieldInfoPropertyInfo之间很常见,但它没有GetValue,因此我无法返回MemberInfo。我一直在阅读有关表达的内容,但不确定他们在这里如何帮助我...

同样,我正在寻找的是(给定一个来源)解析以下内容的能力:X.Y.Z其中X,Y,Z可以是属性或字段。

修改

所以我修改了一些代码来做我想做的事情 - 但这不是你所谓的干净利落的代码,而是太多的代码:

    public static bool TryParse(string path, object start, out PropertyInfo pinfo, out FieldInfo finfo, out object source)
    {
        if (string.IsNullOrEmpty(path))
            throw new ArgumentException();

        var type = start.GetType();
        var paths = path.Split('.');

        source = start;
        pinfo = null;
        finfo = null;

        for (int i = 0; i < paths.Length; i++) {
            var subpath = paths[i];
            pinfo = type.GetProperty(subpath);
            if (pinfo == null) {
                finfo = type.GetField(subpath);
                if (finfo == null)
                    return false;
            }
            if (i < paths.Length - 1) {
                source = pinfo == null ? finfo.GetValue(source) : pinfo.GetValue(source);
                type = source.GetType();
            }
        }
        return true;
    }

用法:

        var game = new GameManager
        {
            player = new Player { gameObject = new GameObject { Name = "Stu" } }
        };

        object source;
        PropertyInfo pinfo;
        FieldInfo finfo;
        if (TryParse("player.gameObject.Name", game, out pinfo, out finfo, out source)) {
            var value = pinfo == null ? finfo.GetValue(source) : pinfo.GetValue(source);
        }

它做了我想要的解析,但必须有更好的东西......

2 个答案:

答案 0 :(得分:2)

我认为您可以尝试使用我的免费开源库Dynamic Expresso

你可以这样写:

var game = new GameManager
    {
        player = new Player { gameObject = new GameObject { Name = "Stu" } }
    };

var interpreter = new Interpreter();
var parameters = new[] {
            new Parameter("game", game)
            };
var result = interpreter.Eval("game.player.gameObject.Name", parameters);

您还可以提取已解析的Expression以获取有关属性/字段的信息,并且还支持更复杂的操作(索引器,函数,...)。已解析的表达式已编译,可以调用一次或多次。

答案 1 :(得分:1)

这里很热,它可以在Expression树(没有检查null并检查属性是否存在):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace ExpressionTrees
{
    public static class ExpressionTreeBuilder
    {
        private static readonly IDictionary<string, Delegate> Lambdas = 
            new Dictionary<string, Delegate>();

        public static T GetValue<T, TInst>(this TInst obj, string propPath, T defVal = default(T))
        {
            var key = String.Format("{0};{1}", propPath, "str");//typeof(T).Name);
            Delegate del;
            if (!Lambdas.TryGetValue(key, out del))
            {
                var instance = Expression.Parameter(typeof(TInst), "obj");

                var currentExpression = 
                    propPath
                    .Split('.')
                    .Aggregate((Expression)instance, Expression.PropertyOrField);

                var lexpr = Expression.Lambda<Func<TInst, T>>(currentExpression, instance);

                del = lexpr.Compile();
                Lambdas.Add(key, del);
            }

            var action = (Func<TInst, T>)del;

            return action.Invoke(obj);
        }

    }
}

使用示例:

var surv = new Survey() { id = 1, title = "adsf" , User = new User() { Name = "UserName 11"}};
var dynamicUserName = surv.GetValue<string, Survey>("User.Name");

但是,当然,最好使用经过良好测试和记录的第三方库。此代码段仅作为示例。