[英]How can I set the variable type with an if/then statement in c#?
我有一个执行SQL查询的函数。 根据注册表值,它将命中SQL Server或SQL Server Compact Edition。 如果使用的是SQL Server CE,则设置recordSet变量的行应如下所示:
SqlCeDataReader recordSet = da.ExecuteSQLCommand(selectCommand);
对于SQL Server,它应如下所示:
SqlDataReader recordSet = da.ExecuteSQLCommand(selectCommand);
我试图将所有这些放在函数开头的if / then语句中,但似乎无法弄清楚如何在if / then中设置Type。 这是我的(部分)代码:
public static string SqlQuery(string selectCommand, int regval)
{
var recordSet = null;
string selectCommand = "select * from whatever";
if (regval == 0)
{
SqlDataReader recordSet = null;
}
else
{
SqlCEDataReader recordSet = null;
}
recordSet = da.ExecuteSQLCommand(selectCommand);
}
问题是,除非我在if / else之前声明recordSet变量,否则之后就不能使用它。 但是,如果我在if / else之前声明它,则无法更改类型。
你不能那样做。 除非您使用dynamic
否则变量的类型实际上是在编译时固定设置的。
您可以使用通用接口IDataReader
。 其他标准的ADO.NET客户端(例如MySQL和SQLite)也实现了此功能。
编辑
这是一个样本
public static string SqlQuery(string selectCommand, int regval)
{
IDataReader recordSet = null;
string selectCommand = "select * from whatever";
recordSet = da.ExecuteSQLCommand(selectCommand);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.