繁体   English   中英

动态创建表达式树

[英]Create Expression Tree dynamically

我有一个主意,想知道它是否可以工作。 我有一个带有属性的简单类,并希望使用表达式生成访问器。 但是最后,我需要获得Func<Test, string>但是使用它们时我不知道类型。 一个小例子

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        test.TestString = "Blubb";
        var actionStub = typeof(Helper).GetMethod("CreatePropertyGetter").MakeGenericMethod(new Type[] { test.GetType(), typeof(string)});
        dynamic action = actionStub.Invoke(null, new object[] {test.GetType(), "TestString"});

        var x = action(test);
    }
}

public class Test
{
    public string TestString { get; set; }
}

public static class Helper
{
    public static Func<TType, TPropValueType> CreatePropertyGetter<TType, TPropValueType>(Type type,
                                                                                  string propertyName)
    {
        PropertyInfo fieldInfo = type.GetProperty(propertyName);
        ParameterExpression targetExp = Expression.Parameter(typeof(TType), "target");

        MemberExpression fieldExp = Expression.Property(targetExp, fieldInfo);
        UnaryExpression assignExp = Expression.Convert(fieldExp, typeof(TPropValueType));

        Func<TType, TPropValueType> getter =
            Expression.Lambda<Func<TType, TPropValueType>>(assignExp, targetExp).Compile();

        return getter;
    }
}

问题是我不能在没有动态的情况下调用表达式,因为我不能简单地将其Func<object, object>Func<object, object>

您正在生成(TType target) => target.Something 相反,应生成(object target) => (object)((TType)target).Something这样可以使用Func<object, object>

目前尚不清楚您到底要什么,但是这里有一个示例,您可以将其设置为Func<object, object>

public static class Helper
{
    public static Func<object, object> CreatePropertyGetter(Type type, string propertyName)
    {
        var fieldInfo = type.GetProperty(propertyName);
        var targetExp = Expression.Parameter(typeof(object), "target");
        var fieldExp = Expression.Property(Expression.ConvertChecked(targetExp, type), fieldInfo);
        var getter = Expression.Lambda<Func<object, object>>(fieldExp,targetExp).Compile();
        return getter;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM