IDataReader.GetOrdinal 或 IDataReader[ColumnName]
我有两种情况从 IDataReader 对象中提取信息
Case - 1 - Length,计算序数,然后解析字符串
public static string GetString(IDataReader rdr, string columnName)
{
int ordinal = rdr.GetOrdinal(columnName);
if (rdr.IsDBNull(ordinal))
{
return string.Empty;
}
return (string)rdr[ordinal];
}
Case - 2,简短的方式,获取数据而不计算序数
public static string GetString(IDataReader rdr, string columnName)
{
return (string)rdr[columnName];
}
应该首选哪种技术以及为什么以及是否有特定上下文?
I have two cases to extract information from the IDataReader object
Case - 1 - Length, calculates ordinal and then parse string
public static string GetString(IDataReader rdr, string columnName)
{
int ordinal = rdr.GetOrdinal(columnName);
if (rdr.IsDBNull(ordinal))
{
return string.Empty;
}
return (string)rdr[ordinal];
}
Case - 2, short way, getting data without calculating ordinal
public static string GetString(IDataReader rdr, string columnName)
{
return (string)rdr[columnName];
}
Which technique should be preferred and why and if any specific context ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SqlDataReader的
this[string name]
看起来像:所以它计算序数内部,使用什么方式没有区别。
更新
您可以将代码重写为:
SqlDataReader's
this[string name]
looks like:so it calculates ordinal internaly, and there is no difference what way to use.
UPDATE
Yo can rewrite your code as:
这是第一种方法的 MSIL 的样子:
对于第二种方法:
所以这些方法肯定不一样。至于哪个更好,您没有说明为什么要计算序数,因此很难说哪个更适合您的情况。
Here's what MSIL looks like for your first method:
And for your second method:
So the methods are definitely not the same. As to which is better, you don't say why you want to calculate the ordinal so it's hard to say which is better for your situation.
我不认为真的有什么区别(他们做同样的事情),第二个对我来说似乎更具可读性,因为“索引”的引入会让那些不知道读者如何工作的人感到困惑。我说隐藏不必要的复杂性。您应该更进一步,使其成为可以在任何地方使用的泛型,如下所示:
调用它很容易:
编辑:
您没有在第二个示例中检查 DBNull,因此转换会因空值而失败。然而,一般来说,这两种方法是相同的。
I don't think there's really a difference (they do the same thing), the second seems more readable to me as the introduction of the 'index' is confusing for those who don't know how the reader is working. Hide needless complexity I say. You should go a step further and make it a generic you can use anywhere, like this:
Invoking it is easy:
Edit:
You're not checking for DBNull in your second example, so the cast would fail on nulls. However, generally speaking the two approaches are the same.