[英]NullReferenceException when trying to send bytes via Bluetooth in C#
這是我第一次使用C#進行藍牙連接。 我試圖通過藍牙從C#編寫的應用程序發送字節(數據類型)。
這是我的代碼:
public class ConnectionManager
{
private StreamSocket socket;
private DataWriter dataWriter;
public void Initialize()
{
socket = new StreamSocket();
}
public void Terminate()
{
if (socket != null)
{
socket.Dispose();
}
}
public async void connect(HostName hostName)
{
if (socket != null)
{
await socket.ConnectAsync(hostName, "1");
dataWriter = new DataWriter(socket.OutputStream);
}
}
//sending data via Bluetooth
public void sendCommand(byte command)
{
dataWriter.WriteByte(command);
}
}
private ConnectionManager connectionManager;
// Constructor
public MainPage()
{
InitializeComponent();
connectionManager = new ConnectionManager();
}
private async void AppToDevice()
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug.WriteLine("No devices found.");
}
else
{
foreach (var pairedDevice in pairedDevices)
{
if (pairedDevice.DisplayName == "HC-06")
{
connectionManager.connect(pairedDevice.HostName);
continue;
}
}
}
}
private void send_Click(object sender, RoutedEventArgs e)
{
byte command = Convert.ToByte(commandTextBox.Text);
connectionManager.sendCommand(command);
}
private void connect_Click(object sender, RoutedEventArgs e)
{
AppToDevice();
}
當我在commandTextBox中輸入一些值(例如1或2)並點擊“發送”按鈕時,應用程序崩潰。 這是錯誤消息: TestBluetooth.DLL中發生類型'System.NullReferenceException'的異常,但未在用戶代碼中處理
有人能幫我嗎?
聽起來像是一個非常基本的錯誤。 某些對象為空。 當您嘗試訪問null的對象上的方法或屬性時,就會發生這種情況。
故障排除:
當您收到一條錯誤消息“未在用戶代碼中處理”時,表示您拋出了異常並且未通過try / catch處理。 我對那里的異步方法有所了解。
如果我曾經玩過線程,那么我總是可以嘗試/捕獲線程代碼中的所有代碼。 我建議在AppToDevice()方法中添加try / catch。 同時將其添加到所有Form事件中。 向用戶顯示錯誤消息或處理錯誤消息,並向用戶隱藏錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.