2

我正在使用 DynamicMethod 进行一些代码生成,我有一个问题可以通过添加一个小状态来轻松解决,比如一个字段。不幸的是,我无法将此状态推送到方法的参数之一中,所以我基本上需要关闭像这个小 lambda 这样的本地:

var i = 0;
return new Func<int>(() => i++);

最简单的方法是什么?

4

1 回答 1

2

I believe you can't do that, at least not directly. DynamicMethod lets you create a single CLR method and nothing else. C# methods don't have that limitation, they are free to create closure types and fields in them and whatever else they need.

To achieve what you want, you could use TypeBuilder to dynamically build a full type with a method and a field.

But a simpler option would be to create the method with the state as a parameter and then use a closure (or, alternatively, a normal object) to capture the state. Something like:

Action<TData> CaptureState<TState, TData>(
    Action<TState, TData> originalAction, TState initialState)
{
    var state = initialState;
    return data => originalAction(state, data);
}

You would then use it like this:

Action<State, string> generated = …;
Action<string> captured = CaptureState(generated, new State());
captured("data1");
captured("data2");

If your method needs to change the value of the state (and not just modify some properties on it), then you would need to use ref parameter for the state, but the principle works the same (it would also mean you would need to use custom delegate type).

于 2012-10-06T15:43:15.427 回答