C#委託的簡單使用

C#利用委託實現將類中數據傳到APP,使用步驟如下:

①在Class中聲明一個委託,再創建一個事件

//Define a delegate
public delegate void Mydelegate(byte[] data = null);
public event Mydelegate ReadValueChanged;

//Define a delegate
public delegate void Mydelegate2(string str);
public event Mydelegate2 NotificationEvent;

②通過委託向調用端發送數據

/// <summary>
/// Read Data
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <returns ></returns>
private void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    byte[] data;
    string strReceiveData = "";

    CryptographicBuffer.CopyToByteArray(args.CharacteristicValue, out data);

    ReadValueChanged(data);

    strLog = "[Info]:Connect the Bluetooth successfully.\r\n";
    NotificationEvent(strLog);
}

③APP端實現委託事件的調用

//Bluetooth Device
BluetoothLEClass BluetoothInstance;

BluetoothInstance.ReadValueChanged += Bluetooth_ReadValue;
BluetoothInstance.NotificationEvent += Bluetooth_NotificationValue;

/// <summary>
/// Read Data
/// </summary>
/// <param name="strLog"></param>
/// <returns ></returns>
private void Bluetooth_NotificationValue(string strLog)
{
    string strLogInfo = strLog;

    //display temperature data
    BeginInvoke(new Action(() =>
    {
        if ("[Info]:Connect the Bluetooth successfully.\r\n" == strLogInfo)
        {
            SearchDeviceBtn.Text = "Disconnect";
        }

        //LogText.Text += logstr;                
        OutStatusLog(strLogInfo);
    }));
}

/// <summary>
/// Read Data
/// </summary>
/// <param name="ReadData"></param>
/// <returns ></returns>
private void Bluetooth_ReadValue(byte[] ReadData)
{
    string strReceiveData = "";         

    strReceiveData = "Receive Data: ";

    for (int i = 0; i < ReadData.Length; i++)
    {
        strReceiveData += ReadData[i].ToString("X") + " ";
    }
    strReceiveData += "\r\n";

    //display temperature data
    BeginInvoke(new Action(() =>
    {
        //LogText.Text += logstr;                
        OutStatusLog(strReceiveData);
    }));
}

這樣在類產生的數據變化就能體現到上層APP中,實現數據的互傳。

下面是委託的另一個用法,委託使用一個函數

//定義一個委託類型,用來保存無參數,無返回值的方法
public delegate void Mydelegate();

static void Main(string[] args)
{ 
    //實例化一個委託類型,將方法M1作爲變量傳遞
    //即md委託保存了M1方法
    Mydelegate md = new Mydelegate(M1);
 
    //調用了MD委託的時候就相當於調用了M1方法
    md();
    Console.WriteLine("OK");
    Console.ReadKey();
}
 
static void M1()
{
    Console.WriteLine("我是一個沒有返回值沒有參數的方法!");
}

其實委託另一個比較常用的功能就是在線程改變控件。

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章