TargetInvocationException Being Thrown c#
本文关键字:Thrown Being TargetInvocationException | 更新日期: 2023-09-27 18:10:32
我有一个调用后台工作人员完成的例程。如下所示,
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;
异常是空引用异常,在设置数据源
时发生。 BatteryNameComparer
的代码
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);
}
}
当您看到TargetInvocationException
时,您应该立即检查它的InnerException
属性,以查找实际抛出的异常。
http://msdn.microsoft.com/en-us/library/system.exception.innerexception (v = vs.110) . aspx
简单地说,TargetInvocationException
只告诉您在某种调用上下文中抛出了另一个异常—这几乎总是跨线程操作或通过反射调用。