检查 DataReader 中是否存在列或不使调试器因某些异常而中断

发布于 2024-07-11 19:13:28 字数 421 浏览 5 评论 0原文

我的代码如下所示:

  //System.Data.IDataRecord dr
  try
  {
       Consolidated = Utility.NullConvert.ToBool(dr[Constants.Data.Columns.cConsolidated], false);
  }
  catch (IndexOutOfRangeException) { } //swallow

我不知道合并列是否会出现在数据读取器中,所以我这样做是为了检查。 它工作得很好(虽然有点hackish)。

但是,当我附加调试器时,只要抛出异常,它就会中断。 非常烦人。

有没有更好的方法来编写该代码; 或者是否有某种 Visual Studio 方式告诉它忽略异常而不中断(但仅限于此;而不是到处)。

I have code that looks like:

  //System.Data.IDataRecord dr
  try
  {
       Consolidated = Utility.NullConvert.ToBool(dr[Constants.Data.Columns.cConsolidated], false);
  }
  catch (IndexOutOfRangeException) { } //swallow

I don't know if the consolidated column will be present in the datareader, so I do that to check. It works fine (is a little hackish, though).

When I attach a debugger though, it breaks on that whenever it throws the exception however. Extremely annoying.

Is there a better way to write that code; or is there some Visual Studio way of telling it to ignore the exception and not break (but only right here; not everywhere).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

浅紫色的梦幻 2024-07-18 19:13:28

是的,您可以使用数据读取器的 GetSchemaTable() 方法来获取列的列表,然后您可以查看该列是否存在。

您可能会发现这个非常相似的问题很有帮助。

Yes, you can use the GetSchemaTable() method of the datareader to get a list of columns, then you can see if that column exists.

You might find this very similar question helpful.

陈甜 2024-07-18 19:13:28

我只需在循环开始时使用 GetOrdinal() 来首先查找列索引(并存储在变量中)。 然后检查是否为>=0。 这也具有提高性能的优点(只要您使用该整数进行所有访问,而不是名称)。

不,没有一种优雅的方法可以忽略特定的异常。 你可以抓住并吞下,但这不是一个好方法。

I would simply use GetOrdinal() at the start of the loop to find the column indexes first (and store in a variable). Then just check whether it is >=0. This has the advantage of improving performance too (as long as you then use this integer for all access, not the name).

And no, there is no elegant way of ignoring a particular exception. You could catch and swallow, but that is not a good approach.

深海蓝天 2024-07-18 19:13:28

您可以简单地使用以下代码:

reader.GetSchemaTable().Columns.Contains("Your_Column")

这将返回一个布尔值。

If reader.GetSchemaTable().Columns.Contains("ContactID") Then
   ' Do something
End If

You can simply use the following code:

reader.GetSchemaTable().Columns.Contains("Your_Column")

This will return a boolean.

If reader.GetSchemaTable().Columns.Contains("ContactID") Then
   ' Do something
End If
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文