0

我有一個例程,這是一個後臺工作人員完成調用。如下;TargetInvocationException被投擲c#

private void BatteryListFetchBackgroundWorkerRunWorkerCompleter(object sender, RunWorkerCompletedEventArgs e) 
{ 
    this.Cursor = Cursors.Default; 
    var sortedList = this.currentBatteries.Values.OrderBy(g => g, new BatteryNameComparer()); //breaks here 

    this.BatteryBindingSource.DataSource = sortedList; 
    if (this.batteryListBox.Items.Count > 0) 
    { 
     this.batteryListBox.SetSelected(0, true); 
    } 

    this.viewScheduleButton.Enabled = true; 
    this.viewDefaultScheduleButton.Enabled = true; 
    this.viewEditScheduleLimits.Enabled = true; 
} 

它打破的路線是;

   this.BatteryBindingSource.DataSource = sortedList; 

唯一的例外是空引用異常,並設置數據源時

每當你看到一個TargetInvocationExceptionBatteryNameComparer

public class BatteryNameComparer : IComparer<Battery> 
{ 
    /// <summary> 
    /// Compares DDSMGroup 
    /// </summary> 
    /// <param name="a">first value for comparison</param> 
    /// <param name="b">second value for comparison</param> 
    /// <returns>An integer indicating the compare result</returns> 
    public int Compare(Battery a, Battery b) 
    { 
     int aId = int.Parse(a.DeviceName.Substring(BatteryOverviewControl.BatteryPrefixSubstring.Length)); 
     int bId = int.Parse(b.DeviceName.Substring(BatteryOverviewControl.BatteryPrefixSubstring.Length)); 

     return aId.CompareTo(bId); 
    } 
} 
+0

在比較器中會發生異常,您可以發佈BatteryNameComparer的源代碼嗎? – MatteoSp

+0

它已發佈,但是當我在電池名稱比較器中放置斷點時,它永遠不會到達 –

+3

在處理異常時總是發佈堆棧跟蹤。 – khellang

回答