简体   繁体   English

动态创建表达式树

[英]Create Expression Tree dynamically

I had an idea and want to know if it can work. 我有一个主意,想知道它是否可以工作。 I have a simple classes with properties and want to generate accessors with Expressions. 我有一个带有属性的简单类,并希望使用表达式生成访问器。 But in the end I need to get a Func<Test, string> but I don't know the types when I use them. 但是最后,我需要获得Func<Test, string>但是使用它们时我不知道类型。 A small example 一个小例子

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

The problem is I cant call the expression without dynamic, because I cant simple cast it to Func<object, object> 问题是我不能在没有动态的情况下调用表达式,因为我不能简单地将其Func<object, object>Func<object, object>

You're generating (TType target) => target.Something . 您正在生成(TType target) => target.Something Instead, generate (object target) => (object)((TType)target).Something so that you can use Func<object, object> . 相反,应生成(object target) => (object)((TType)target).Something这样可以使用Func<object, object>

It's not clear what exactly you are asking for, but here is an example how you can make it 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