动态类表达式(Expression with dynamic class)

2019-10-22 12:33发布

我试图让表达与继承动态类工作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);
            }
}

在返回的错误如下:

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使用非类型化特性的动态对象?

Answer 1:

现在,这是我第一次玩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

需要注意的是该属性的名称是“有线”到表达式树,并且无法通过函数的参数选择...



文章来源: Expression with dynamic class