如何调用Action参数中的参数

本文关键字:参数 Action 何调用 调用 | 更新日期: 2023-09-27 18:13:34

我有以下代码。编译器给出

Error   CS7036  There is no argument given that corresponds to the required formal parameter 'parameter' of 'SARSystem.WithLock<T>(SARSystem.Locks, Action<T>, T)

public class Locks
{         
    private Locks() {}
    private static object _lock = new object();
    public static object Lock { get { return _lock; } }
}
public static void WithLock<T>(Locks theLock, Action<T> action, T param)
{
    Monitor.Enter(theLock);
    {
        try
        {
            action(param);
        }
        finally
        {
            Monitor.Exit(theLock);
        }
    }
}
private static Locks tradingSystemLock;
public void OnQuote(TickPriceMessage tp)
{
    // How do I call WithLock? This doesn't work.
    WithLock(tradingSystemLock, delegate (TickPriceMessage tpm) { Console.WriteLine(tp.ToString()); });                  
}

如何调用Action<T>参数中的参数

您的Action调用没有问题,但您如何调用您的函数:

WithLock(tradingSystemLock, 
    delegate (TickPriceMessage tpm) { Console.WriteLine(tp.ToString()); },
    tp);

如果你费心阅读/发布你得到的错误信息,这将立即明显。

作为旁注,不仅是你的WithLock<>无用,这也是错误的-我认为你想锁定theLock.Lock,而不是theLock

根据Lee的注释,您的方法有三个参数:

WithLock<T>(Locks theLock, Action<T> action, T param)

锁、委托和参数化。

下面的代码应该可以工作:

public void OnQuote(TickPriceMessage tp)
{        
    WithLock<TickPriceMessage>(tradingSystemLock, (tpm) => {Console.WriteLine(tpm.ToString());}, tp);                  
}