Lambda/Action 有本地参考

Lambda/Action with a local ref

如何将 ref 传递给 lambda?我看过建议委托的帖子,但我无法让它工作..

我试过:

public class State<T>
{
  public State() { }
  public State(T t) { this.t = t; }
  readonly object theLock = new object();
  T t;

  public void Lock(Action<ref T> action) { lock (theLock) action(ref t); }
}

然而这并没有编译,我得到 'unexpected token ref'

然后我尝试了:

public class State<T>
{
  public State() { }
  public State(T t) { this.t = t; }
  readonly object theLock = new object();
  T t;

  public delegate void ActionRef<X>(ref X t);
  public void Lock(ActionRef<T> action) { lock (theLock) action(ref t); }
}

可以编译但我无法使用它

如果我尝试:

  var v = new State<int>(5);
  v.Lock(t => t + 1);

我得到 Parameter 1 must be declared with the 'ref' keyword

如果我尝试:

  var v = new State<int>(5);
  v.Lock(ref t => t + 1);

我得到A ref or out value must be an assignable variable

我怎样才能让它工作?那就是将一个 Action 传递给 Lock 来锁定锁,然后使用 ref 调用 lambda?

(在 VS19 社区预览版 .NET Core 控制台应用程序中测试)

(这与 Cannot use ref or out parameter in lambda expressions 不同,因为它是关于在闭包中使用 ref 的 lambda)

(归功于 PetSerAI ..)

我很接近,State<T>是一样的:

public class State<T>
{
  public State() { }
  public State(T t) { this.t = t; }
  readonly object theLock = new object();
  T t;

  public delegate void ActionRef(ref T t);
  public void Lock(ActionRef action) { lock (theLock) action(ref t); }
}

但是使用起来是这样的:

var s = new State<int>(5);
s.Lock((ref int v) => v=v+3);

这里要完成的是ReadOnlyState<T>:

public class ReadOnlyState<T>
{
  public ReadOnlyState(T t) { this.t = t; }

  readonly object theLock = new object();
  readonly T t;
  public delegate void ActionRef(in T t);
  public void Lock(ActionRef action) { lock (theLock) action(in t); }
}

var ros = new ReadOnlyState<int>(5);
ros.Lock((in int v) => {
   v.f();
   v=2; // does not compile
});