动态类表达 [英] Expression with dynamic class
本文介绍了动态类表达的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使 Expression 与动态类一起工作,这些动态类像这样继承了DynamicObject
:
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);
}
}
返回时的错误如下:
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
?
Is there a way of creating an Expression
using a dynamic object with untyped properties?
推荐答案
现在,这是我第一次与Expression.Dynamic
一起玩...您想要这样做吗?
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...
这篇关于动态类表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文