You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BLE设备(RFduino)配对报错<Name>5_1 is null,求解决方案

解决BLE配对时的"5_1 is null"空引用错误

嘿,我一眼就揪出问题根源了——你在设备发现和配对环节用的对象类型完全不匹配,直接导致了空引用错误!

问题拆解

  • 你的设备发现代码里,items集合存的仅仅是设备的LocalName字符串(eventArgs.Advertisement.LocalName)
  • 但配对代码里,你把listBox1.SelectedItem强制转换成BluetoothLEDeviceDisplay类型——这肯定行不通啊!选中的项本质是个字符串,转换后Name直接变成null,调用Name.DeviceInformation自然会触发空引用报错。

正确修复步骤

1. 修改设备发现逻辑,存储完整的设备信息对象

别只存设备名称字符串,要创建包含DeviceInformation的BluetoothLEDeviceDisplay实例(或自定义类),这样后续配对时能直接拿到可用的设备核心信息。

修改后的设备发现代码示例:

// 先确保items是存储BluetoothLEDeviceDisplay的集合,比如List<BluetoothLEDeviceDisplay>
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
    // 通过蓝牙地址获取完整的设备信息
    var bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync(eventArgs.BluetoothAddress);
    var deviceDisplay = new BluetoothLEDeviceDisplay(bleDevice.DeviceInformation);
    
    // 用设备ID判断是否已存在,避免重复添加
    if (!items.Any(d => d.DeviceInformation.Id == deviceDisplay.DeviceInformation.Id))
    {
        items.Add(deviceDisplay);
        // 蓝牙回调在后台线程,更新UI必须切回UI线程
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => 
        {
            listBox1.ItemsSource = items;
        });
    }
}

2. 调整配对代码,直接使用正确类型的选中项

现在listBox1的项是完整的BluetoothLEDeviceDisplay实例,转换不会再失败,还可以加个非空判断做防御:

var selectedDevice = listBox1.SelectedItem as BluetoothLEDeviceDisplay;
if (selectedDevice != null)
{
    DevicePairingResult result = await selectedDevice.DeviceInformation.Pairing.PairAsync();
    updateUI($"配对状态:{result.Status}");
}
else
{
    updateUI("请先选择一个要配对的设备");
}

额外提醒

  • 确保BluetoothLEDeviceDisplay类正确封装了DeviceInformation属性,能直接访问到设备的配对对象
  • 蓝牙广告回调是后台线程触发的,更新UI一定要用Dispatcher切回UI线程,避免跨线程报错
  • 配对前可以先检查设备的配对状态,避免无效操作

内容的提问来源于stack exchange,提问作者Yann Kang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:19:38