动态表达式 class

Expression with dynamic class

我正在尝试使 Expressions 与继承 DynamicObject 的动态 类 一起工作,如下所示:

    // Dynamic class defintion
    public class DynamicClass1 : DynamicObject { // Code here... }

    // Here is where I try to create where "someproperty" is untyped and the DynamicClass1 is referenced (not shown here)
        public static IQueryable DoStuff(this IQueryable source, string predicate, params object[] values)
        {
            LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
                return Expression.Call(
                    typeof(Queryable), "DoStuff",
                    new Type[] { source.ElementType },
                    source.Expression, Expression.Quote(lambda));
        }

    // Later in the DoStuff() parsing of the Lambda expression the error happens here
        Expression ParseMemberAccess(Type type, Expression instance)
        {
            if (type.IsSubclassOf(typeof(System.Dynamic.DynamicObject)) && instance != null)
            {
                /* 
                * Dynamic object found; so create a dummy property since we can't know if it exists or not before after 
                * we try to retrieve it from the storage.
                */
                return Expression.Property(instance, id);
            }
}

return处报错如下:

An exception of type 'System.ArgumentException' occurred in System.Core.dll but was not handled in user code. Additional information: Property "someproperty" is not defined for type DynamicClass1.

有没有办法使用具有未类型化属性的动态对象创建 Expression

现在,这是我第一次玩Expression.Dynamic...你想要这个吗:

var binder = Binder.GetMember(
    CSharpBinderFlags.None, 
    "Value", 
    typeof(Program), // or this.GetType() 
    new[] { CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null) });

var par = Expression.Parameter(typeof(object));

Func<dynamic, dynamic> f = Expression.Lambda<Func<dynamic, dynamic>>(
    Expression.Dynamic(binder, typeof(object), par), 
    par)
    .Compile();

dynamic obj = new ExpandoObject();
obj.Value = "Hello";
object value = f(obj); // Hello

注意 属性 的名称是 "cabled" 到表达式树中,不能通过函数的参数选择...