gpt4 book ai didi

c# - 将 SqlDataReader 传递为用作转换的参数

转载 作者:行者123 更新时间:2023-12-03 19:08:45 25 4
gpt4 key购买 nike

为了转换 SqlDataReader 的数据,我做了这些(常见数据类型的示例):

string name = reader["name"].ToString();  //for string


int i = 0; i = int.TryParse(reader["i"].ToString(), out i); //for int
int i = reader.GetInt32(reader.GetOrdinal("i")); //or this again for int

bool b = reader.GetBoolean(reader.GetOrdinal("b")); // for boolean

我想创建一个具有这些功能的类:

public static class gd{
public static bool Bool(SqlDataReader rd, string name)
{
return rd.GetBoolean(rd.GetOrdinal(name));
}
public static int Int(SqlDataReader rd, string name)
{
int i=0;
i = int.TryParse(reader["i"].ToString(), out i);
return i;
}
}

然后只需使用:

int i=c.Int(reader,"i");
bool b=c.Bool(reader,"b");
DateTime dt = c.Date(reader,"dt");

我想知道将 datareader 作为参数传递是个好主意吗?谁有更好的转换数据读取器数据的想法?

最佳答案

是的,可以将 DataReader 作为参数传递(与任何其他引用类型一样)。当您传递 reader 时,仅将对它的引用传递给另一个方法。并且可以使用方法使您的代码更具可读性和可维护性。

您可以编写扩展方法来简化您的代码:

public static class Extensions
{
public static bool GetBoolean(this IDataReader reader, string name)
{
return reader.GetBoolean(reader.GetOrdinal(name));
}

public static int GetInt32(this IDataReader reader, string name)
{
return reader.GetInt32(reader.GetOrdinal(name));
}
}

用法如下:

int i = reader.GetInt32("i");
bool b = reader.GetBoolean("b");

关于c# - 将 SqlDataReader 传递为用作转换的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19518945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com