如果 xml 文本编写器为 null,则跳过项目
我有 Windows 窗体 C# 应用程序,它从 GUI 获取值并使用 XML 文本编写器从中创建 XML 文件。问题是其中一些值是可选的,当用户将它们留空时,应用程序会收到空引用异常,因为文本流为空。在不检查每个值的情况下,是否有一种方法可以异常处理整个事件以忽略空值? Try-catch 在这方面似乎不起作用,因为它不会将光标返回到下一条语句。抱歉,如果这是一个n00bish问题!
I have Windows form C# application that takes values from the GUI and uses XML Textwriter to create an XML file from them. The problem is some of these values are meant to be optional and when the user leaves them blank, the application gets a null reference exception because the text stream is null. Without doing a check on every value, is there a way to exception handle the whole thing to ignore null values? Try-catch doesn't seem work in this regard because it won't return the cursor to the next statement. Sorry if this is a n00bish question!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许您可以使用 C# 类来表示要保存的数据,并使用 XmlSerializer 来序列化所有这些(使用 XmlTextWriter 作为输入),因为 Xml 序列化可以优雅地隐式处理 null。
Maybe you could use a C# class that represents the data what you want to save, and an XmlSerializer to serialize all this (with an XmlTextWriter as an input) because Xml Serialization handles null implicitely gracefully.
使用异常来处理这个问题会导致各种各样的问题。对于不需要的值,您需要花时间用
if(...)
包装对writer.Write(....)
的调用。Using exceptions to handle this will lead to all sorts of issues. You need to spend the time to wrap the calls to
writer.Write(....)
withif(...)
for values that are not required.