簡體   English   中英

向集合添加方法調用

[英]Adding a method call to a collection

給定一種情況,我有一個方法SetFooInDevice() ,我使用屬性作為參數之一來調用它:

public class Program
{
    public static byte Foo { get; set; }

    public static void SetFooInDevice(System.IO.Ports.SerialPort sp, byte foo) 
    {
        var txBuffer = new List<byte>();
        // Format message according to communication protocol
        txBuffer.Add(foo);
        sp.Write(txBuffer.ToArray(), 0, txBuffer.Count);
    }

    public static void Main()
    {
        var _rnd = new Random();
        var _serialPort = new System.IO.Ports.SerialPort("COM1", 9600);
        _serialPort.Open();
        for (int i = 0; i < 100; i++)
        {
            Foo = (byte)_rnd.Next(0, 255);
            SetFooInDevice(_serialPort, Foo);  // <-- How to add this call to a collection?
            System.Threading.Thread.Sleep(100);
        }
    }
}

是否可以將方法調用添加到集合中,以便以后在遍歷該集合時可以執行該方法調用?

我希望能夠將對各種方法的調用添加到集合中,以便在滿足條件(串行端口打開,時間間隔已過去等)下可以運行並稍后執行。

嘗試這個:

public static byte Foo { get; set; }

public static void SetFooInDevice(System.IO.Ports.SerialPort sp, byte foo)
{
    var txBuffer = new List<byte>();
    // Format message according to communication protocol
    txBuffer.Add(foo);
    sp.Write(txBuffer.ToArray(), 0, txBuffer.Count);
}

public static void Main()
{
    List<Action> listActions = new List<Action>(); // here you create list of action you need to execute later
    var _rnd = new Random();
    var _serialPort = new System.IO.Ports.SerialPort("COM1", 9600);
    _serialPort.Open();
    for (int i = 0; i < 100; i++)
    {
        Foo = (byte)_rnd.Next(0, 255);
        var tmpFoo = Foo; // wee need to create local variable, this is important
        listActions.Add(() => SetFooInDevice(_serialPort, tmpFoo));
        System.Threading.Thread.Sleep(100);
    }

    foreach (var item in listActions)
    {
        item(); // here you can execute action you added to collection
    }
}

您可以在MS docs Use Fariance for Func and Action Generic Delegates上進行檢查

您可以為此使用Action委托,如下所示

    private List<Action<System.IO.Ports.SerialPort, byte>> methodCalls
        = new List<Action<System.IO.Ports.SerialPort, byte>>();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM