use*_*636 0 c# sql stack-overflow
我有以下简单的类来管理我的SQL数据库操作
public class DatabaseManager
{
private string CommandString
{
set { CommandString = GetCommandString(commandtype); }
get { return CommandString; }
}
public string commandtype
{
set;
get;
}
public DatabaseManager(string commandtype)
{
commandtype = this.commandtype;
CommandString = GetCommandString(commandtype);
}
public DatabaseManager()
{
}
public static SqlConnection CreateConnection()
{
return new SqlConnection(Properties.Settings.Default.connectionString);
}
//returns a datatable if the command requires a dataadapter
public DataTable ExecuteSelect()
{
var x = new DataTable();
using (var da = new SqlDataAdapter(CommandString, DatabaseManager.CreateConnection()))
{
da.Fill(x);
}
return x;
}
private string GetCommandString(string commandtype)
{
switch (commandtype)
{
// select commands
case ("SELECTMARGINS"): CommandString = "select * from margins"; break;
case ("SELECTRANKS"): CommandString = "select * from ranks"; break;
/...and other commands
return CommandString;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在获得Stackoverflow异常 get { return CommandString; }
你不能拥有一个属性返回(它创建一个无限循环).
private string _CommandString;
public string CommandString
{
set { _CommandString = GetCommandString(commandtype); }
get { return _CommandString; }
}
Run Code Online (Sandbox Code Playgroud)
这个get功能是你的问题
get { return CommandString; }
Run Code Online (Sandbox Code Playgroud)
这是以下的士气
public string GetCommandString() {
return GetCommandString();
}
Run Code Online (Sandbox Code Playgroud)
这将创建无限递归,最终StackOverflowException将抛出.您需要更改get和set操作支持字段,该字段保存实际值并使用它
private string _commandString;
public string CommandString {
get { return _commandString; }
set { _commandString = GetCommandString(commandtype); }
}
Run Code Online (Sandbox Code Playgroud)