简体   繁体   English

代表USB设备的C#类

[英]C# class representing a USB device

I'm writing a wrapper class in C# for a USB device (using P/Invoke to communicate with it). 我正在用C#为USB设备编写包装类(使用P / Invoke与之通信)。 The device needs to be sent an open message before use, and a close method when it's done with. 设备需要在使用前发送打开消息,并在完成后发送关闭方法。 In my constructor I want to try to open the device and return null if that call fails for whatever reason. 在我的构造函数中,我想尝试打开设备,如果由于某种原因该调用失败,则返回null I'll also write a Dispose() which calls the close method on the device. 我还将编写一个Dispose() ,它在设备上调用close方法。

Is this a sensible way to code it? 这是一种明智的编码方式吗? Or should I have a separate ConnectToDevice method? 还是我应该有一个单独的ConnectToDevice方法?

By putting it in the constructor I hope users of my class can simply write: 通过将其放入构造函数中,希望类的用户可以简单地编写:

USBDevice myDevice = new USBDevice()

if (myDevice != null) {
  myDevice.PerformAction();
  myDevice.Dispose();
  myDevice = null;
}

If your constructor fails the reference will always be null. 如果您的构造函数失败,则引用将始终为null。 However, if you have allocated some disposable resources prior to the error, the caller can't call Dispose on the instance since he has no reference to it. 但是,如果您在错误之前分配了一些可使用的资源,则调用者无法在实例上调用Dispose,因为他没有对该实例的引用。 Thus, if you want to do this in the constructor, you need to make sure the constructor fails gracefully. 因此,如果要在构造函数中执行此操作,则需要确保构造函数正常失败。

To keep things simple, I would probably go with a Connect method instead. 为了简单起见,我可能会改用Connect方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM