繁体   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