向集合添加方法调用

时间:2018-03-13 08:04:44

标签: c# methods

鉴于我有一个方法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);
        }
    }
}

是否可以将方法调用添加到集合中,以便稍后在集合中运行时可以执行方法调用?

我希望能够将对各种方法的调用添加到集合中,如果满足条件(串行端口打开,时间间隔已经过去等),我可以运行并稍后执行。

2 个答案:

答案 0 :(得分:2)

试试这个:

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文档Using Variance for Func and Action Generic Delegates

上查看此内容

答案 1 :(得分:0)

您可以将Action委托用于此目的,如下所示

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