2016-07-13 152 views
0

我使用C#在Windows 10中查找蓝牙低Enegergy设备当我运行下面的代码,我遇到了这样的错误:C#扫描蓝牙LE设备

"An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll but was not handled in user code".

错误的行Debug.WriteLine("Found device: " + devices[0].Id);

我不知道它为什么超出范围。谢谢!

namespace BluetoothLE 
    { 
     /// <summary> 
     /// Interaction logic for MainWindow.xaml 
     /// </summary> 
     public partial class MainWindow : Window 
     { 

      public MainWindow() 
      { 
       InitializeComponent(); 
      } 

      private async void LookForPairedDevices() 
      { 

       // Get BLE devices paired with Windows 
       DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); 

       Debug.WriteLine("Found device: " + devices[0].Id); 


      } 
     } 

    } 
+0

'DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()'返回任何设备,因此试图访问索引0(第一个项目)抛出一个异常 –

回答

3

你的错误是在这条线:

Debug.WriteLine("Found device: " + devices[0].Id); 

如果调试你的代码,你会看到devices具有长度为0,而你试图访问属性id第一个(不存在)。

你可能要考虑使用foreach循环,看看返回什么像这样:

foreach(var device in devices){ 
    Debug.WriteLine("Found device: " + device.Id); 
} 
+0

如果其中任何一个返回null,你将得到一个空引用异常,而不是参数超出范围,这个错误是关于访问比存在更多的项目。 –

+0

你是对的,我会编辑 –

+0

Thx为解释。 – QuickLearner