[英]How can I set the variable type with an if/then statement in c#?
I have a function which performs an SQL query. 我有一个执行SQL查询的函数。 Depending on a registry value, it will either hit SQL Server or SQL Server Compact Edition.
根据注册表值,它将命中SQL Server或SQL Server Compact Edition。 If it is using SQL Server CE, the line setting the recordSet variable should read like this:
如果使用的是SQL Server CE,则设置recordSet变量的行应如下所示:
SqlCeDataReader recordSet = da.ExecuteSQLCommand(selectCommand);
For SQL Server, it should read like this: 对于SQL Server,它应如下所示:
SqlDataReader recordSet = da.ExecuteSQLCommand(selectCommand);
I am trying to put all this in an if/then statement at the beginning at the function but cannot seem to figure out how to set the Type within the if/then. 我试图将所有这些放在函数开头的if / then语句中,但似乎无法弄清楚如何在if / then中设置Type。 Here is my (partial) code:
这是我的(部分)代码:
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);
}
The problem is that unless I declare the recordSet variable before the if/else, I cannot use it after. 问题是,除非我在if / else之前声明recordSet变量,否则之后就不能使用它。 However, if I declare it before the if/else, I cannot change the type.
但是,如果我在if / else之前声明它,则无法更改类型。
You can't do that. 你不能那样做。 Variables' types are really set in stone at compile time unless you use
dynamic
. 除非您使用
dynamic
否则变量的类型实际上是在编译时固定设置的。
You could use the common interface IDataReader
. 您可以使用通用接口
IDataReader
。 Other standard ADO.NET clients such as for MySQL and SQLite implement this too. 其他标准的ADO.NET客户端(例如MySQL和SQLite)也实现了此功能。
Edit 编辑
Here is a sample 这是一个样本
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.