Expression with dynamic class

折月煮酒 提交于 2019-12-24 17:30:01

问题


I'm trying to make Expressions work with dynamic classes that inherits DynamicObject like this:

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

The error at the return is as follows:

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.

Is there a way of creating an Expression using a dynamic object with untyped properties?


回答1:


Now, this is the first time I play with Expression.Dynamic... do you want this:

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

Note that the name of the property is "cabled" into the expression tree, and can't be selected through a parameter of the function...



来源:https://stackoverflow.com/questions/29431031/expression-with-dynamic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!