简体   繁体   中英

How to call Action<T> parameter in a generic method?

I have the following code. The compiler gives

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

Nothing wrong with your Action call, but with how you call your function:

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

Which would be immediately apparent if you bothered to read/post the error message you got.

As a side note, not only is your WithLock<> useless, it's also wrong -- I think you wanted to lock on theLock.Lock , not on theLock . Understandable, given the descriptive names you give variables.

Based on Lee comment, your method takes three arguments:

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

lock, delegate and param.

The following should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM