簡體   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