簡體   English   中英

如何將方法轉換為事件?

[英]How can I transform method into an event?

如何將此方法變成事件?

BarcodeScannerRenderer.cs:

void IScanSuccessCallback.barcodeDetected(MWResult result)
{
   if (result != null)
   {
       try
       {
           var scan = Element as BarcodeScannerModal;
           if (scan == null)
           return;
       }
       catch (Exception ex)
       {
           System.Diagnostics.Debug.WriteLine(ex.Message);
       }
   }
}

並將結果的值傳遞給另一個類,特別是在這里:

(BarcodeScanner.cs)

public async Task<object[]> GetResult()
    {
        TaskCompletionSource<object[]> tcs = new TaskCompletionSource<object[]>();
        scanPage.OnScanResult += async (result) =>
        {
            object[] scanResult = new object[2];
            SharedAppSettings.Sounds.PlayBeep();
            scanResult[0] = resultFinal.text;
            scanResult[1] = resultFinal.typeText;
            await PopupNavigation.PopAsync();

            tcs.SetResult(scanResult);
        };
        return await tcs.Task;
    }

如果您想知道我使用的是哪種類型的條形碼掃描儀,那就是 Manatee Works 條形碼掃描儀。

這個答案可能必須適應問題的變化,所以不要認為它是完整的:

要引發事件,您可以執行以下操作:

// Given you have a custom EventArgs class ...
// Define an event on which clients can register their handlers
public event EventHandler<BCDetectedEventArgs> BarcodeDetected;

// infoObject should probably be of the type what `scan` is.
protected virtual void OnBarcodeDetected( object infoObject ) 
{
    // Check if there is at least one handler registered
    var handler = BarcodeDetected;
    if( handler != null )
    {

         handler(this, new BCDetectedEventArgs(infoObject));
    }
}

void IScanSuccessCallback.barcodeDetected(MWResult result)
{
   if (result != null)
   {
       try
       {
           var scan = Element as BarcodeScannerModal;
           if (scan == null)
              return;
           else
              OnBarcodeDetected( scan );
       }
       catch (Exception ex)
       {
           System.Diagnostics.Debug.WriteLine(ex.Message);
       }
   }
}

另見參考https://msdn.microsoft.com/en-us/library/db0etb8x(v=vs.110).aspx

BarcodeScanner.cs 中的部分有點棘手,因為您的代碼段建議采用“輪詢”設計。 您首先必須適應從上面的代碼片段注冊事件,並在適當的處理程序方法中對事件采取行動。

暫無
暫無

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

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