如何在泛型方法中调用Action <t>参数?

时间:2015-09-20 22:07:12

标签: c# generics

我有以下代码。编译器提供

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()); });                  
}

2 个答案:

答案 0 :(得分:3)

您的Action电话没有问题,但是如何调用您的功能:

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

如果您不愿意阅读/发布您收到的错误消息,这将立即显现出来。

作为旁注,不仅你的WithLock<>无用,而且也是错误的 - 我想你想锁定theLock.Lock,而不是theLock。可以理解,给定描述性名称,您可以给出变量。

答案 1 :(得分:1)

根据Lee评论,您的方法有三个参数:

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

锁定,委托和参数。

以下内容应该有效:

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