在 C# 中将错误消息与错误代码关联的最佳方法是什么?
我有一个用 C#.NET 编写的软件,它通过 USB 与设备通信。当出现问题时,设备会设置一个错误代码,我的软件会以整数的形式读取该错误代码。我想在我的 C# 程序中存储与特定固件错误代码相关的错误消息。存储这些的最佳方式是什么?
有人告诉我,一个好的方法是使用资源文件。使用资源文件有什么好处?有更好的方法吗?
I have a piece of software written in C#.NET that communicates with a device via USB. When a problem occurs the device sets an error code which is read by my software in the form of an integer. I want to store error messages in my C# program that correlate with the specific firmware error codes. What is the best way to store these?
I have been told that a good approach would be to use a Resource file. What are the benefits of using a resource file? Is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议也使用资源文件。一项主要好处是本地化(使用不同的语言)。即使您现在不想使用多种语言,您也可以在以后灵活地添加它们。另一个好处是简单的 .NET/c# 集成。
此外,当需要更改消息时,可以轻松访问资源文件。
I would suggest using a Resource File as well. One key benefit is localization (using different languages). Even if you don't want to use multiple languages today, you give yourself the flexibility to add them later. Another benefit is the simple .NET/c# integration.
Also, resource files are easy to get to when it comes time to change a message.
答案取决于您的需求。特定的错误消息是否需要更新?您是否需要动态添加新的错误代码/消息对的能力?您需要本地化错误消息吗?
最简单的方法就是使用 IDictionary 来硬编码错误代码/消息值。这意味着任何更新都需要您重新编译和重新部署您的应用程序。
资源文件将是另一种选择。在这种情况下,您可以将代码/消息对存储在资源文件中,并且您的应用程序将使用错误代码作为键来查找适当的错误消息值。这将允许您动态添加代码/消息对,并通过为您需要支持的每种语言创建单独的资源文件来轻松本地化。
第三个选项与第二个选项类似,是将错误代码/消息对存储在数据库表中。您的应用程序很可能已经与数据库通信,因此这可能是比资源文件更简单的选项,至少从部署方面来看。但这将使本地化变得更加困难。
如果是我的话,如果我认为以后需要本地化,我会选择资源文件,如果不需要,我会选择数据库。
The answer depends on your needs. Will the error message for a specific ever need to be updated? Will you need the ability to add new error code/message pairs dynamically? Will you need to localize the error messages?
The simplest method is just to hard the error code/message values using an IDictionary. That would mean that any updates would require you to recompile and redeploy your application.
Resource files would be another option. In this instance, you'd store the code/message pairs in the resource file, and your application would use the error code as the key to find the appropriate error message value. This would allow you to dynamically add code/message pairs and would make it easy to localize by creating a separate resource file for each language you need to support.
A third option, similar to the second, would be to store the error code/message pairs in a database table. Your application is, most likely, already talking to a database, so this may be a simpler option than resource files, at least from a deployment aspect. This would make localization more difficult, though.
If it were me, I would choose resource files if I thought there would be a need to localize in the future, and the database if I didn't.