visual-studio 检查 DataReader 中是否存在列,或者在某些异常时不使调试器中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/403215/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check for existence of column in DataReader OR not make debugger break on certain exceptions
提问by Tom Ritter
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).
我不知道合并列是否会出现在数据读取器中,所以我这样做是为了检查。它工作正常(虽然有点hackish)。
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).
有没有更好的方法来编写该代码;或者是否有一些 Visual Studio 方法可以告诉它忽略异常而不是中断(但仅在此处;并非无处不在)。
采纳答案by Mitchel Sellers
Yes, you can use the GetSchemaTable() method of the datareader to get a list of columns, then you can see if that column exists.
是的,您可以使用数据读取器的 GetSchemaTable() 方法获取列列表,然后您可以查看该列是否存在。
You might find this very similar questionhelpful.
您可能会发现这个非常相似的问题很有帮助。
回答by Marc Gravell
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).
我会简单地GetOrdinal()在循环开始时使用首先查找列索引(并存储在变量中)。然后检查它是否是>=0。这也具有提高性能的优点(只要您随后将这个整数用于所有访问,而不是名称)。
And no, there is no elegant way of ignoring a particular exception. You could catch and swallow, but that is not a good approach.
不,没有忽略特定异常的优雅方式。你可以抓住并吞下,但这不是一个好方法。
回答by Kevin Dark
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

