gpt4 book ai didi

c# - 如何通过表达式树生成的委托(delegate)来调用自己?

转载 作者:太空狗 更新时间:2023-10-29 23:49:06 26 4
gpt4 key购买 nike

现在我要将表达式树编译成一个委托(delegate)来动态生成代码,但是我遇到了一个问题。我必须在表达式树中调用一个方法,这正是尚未动态编译的表达式树委托(delegate)。我该怎么办?

我想从表达式树中生成如下代码:

int i = 0;
Action ac = null;

ac = () =>
{
//if (i-- > 0) condition
ac();
};

下面的代码不起作用,会提示ac为null

static Action ac = Build();
static Action Build()
{
return Expression.Lambda<Action>(
Expression.Call(
Expression.Constant(ac), //throw ac is null
typeof(Action).GetType().GetMethod("Invoke")
)
).Compile();
}

最佳答案

表达式的问题是你只能按值传递变量,所以你需要一些技巧来传递引用。你可以这样做:

Action<Node> ac = null;
Func<Action<Node>> getAction = () => ac;

然后像那样构建表达式:

ac = () =>
{
//if (i-- > 0) condition
getAction()();
};

另一种选择是将 Action 包装在某个对象中:

Wrapper<Action> = new Wrapper();
ac = () =>
{
//if (i-- > 0) condition
wrapper.Value();
};
wrapper.Value = ac;

示例代码如下:

    class Wrapper<T>
{
public T Value { get; set; }
}

static void Main(string[] args)
{
Node root = new Node
{
Name = "First",
Next = new Node {Name = "Second"}
};

var method = Build();
method(root);
}

class Node
{
public string Name { get; set; }
public Node Next { get; set; }
}

static Action<Node> Build()
{
var wrapper = new Wrapper<Action<Node>>();
var param = Expression.Parameter(typeof(Node), "node");
var expr = Expression.Lambda<Action<Node>>(
Expression.Block(
// Console.WriteLine("Node name: {0}", node.Name);
Expression.Call(
typeof(Console),
"WriteLine",
Type.EmptyTypes,
Expression.Constant("Node name: {0}"),
Expression.Property(param, "Name")
),
// if (node.Next != null) wrapper.Value(node.Next)
Expression.IfThen(
Expression.ReferenceNotEqual(Expression.Property(param, "Next"), Expression.Constant(null)),
// wrapper.Value(node.Next)
Expression.Invoke(
// wrapper.Value
Expression.Property(Expression.Constant(wrapper), "Value"),
// node.Next
Expression.Property(param, "Next")
)
)
),
param
);

return wrapper.Value = expr.Compile();
}

关于c# - 如何通过表达式树生成的委托(delegate)来调用自己?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54194178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com