2013-03-07 38 views
0

我有以下簡單的類來管理我的SQL數據庫操作#1異常的財產

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; 
     } 

    } 

我得到的get { return CommandString; }

+1

你在CommandString'的'GET無限循環運行,因爲回報'CommandString'調用它自己吸氣。介紹一個支持領域。 '私人字符串_commandString'。 – publicgk 2013-03-07 18:51:09

回答

5

get功能是你的問題

get { return CommandString; } 

這是士氣相當於以下

public string GetCommandString() { 
    return GetCommandString(); 
} 

這的將會創建無限遞歸併最終形成StackOverflowException將被拋出。您需要更改getset對持有的實際價值和使用支持字段操作,與其

private string _commandString; 
public string CommandString { 
    get { return _commandString; } 
    set { _commandString = GetCommandString(commandtype); } 
} 
1

出現StackOverflow例外,不能設置或連得CommandString,在這種情況下你必須創建一個私有變量。

private string _commandString; 
public string CommandString 
{ 
    set { _commandString = GetCommandString(commandtype); } 
    get { return _commandString; } 
} 

什麼在你當前的代碼發生的事情是,你正在做這樣的事情:

CommandString = "x"; 

這就要求

CommandString = GetCommandString(type); 

這就要求

CommandString = GetCommandString(type); 

等。 ...所以它一直循環直到它溢出。私有變量讓你從設置相同的屬性一遍又一遍

此外,它看起來像你從來沒有真正使用過進入設置功能,這似乎是一個錯誤的value

5

你不能有一個屬性返回本身(它創建一個無限循環)。

private string _CommandString; 
    public string CommandString 
    { 
     set { _CommandString = GetCommandString(commandtype); } 
     get { return _CommandString; } 
    } 
1

你不能讓Get函數返回它自己,它只會導致它無限嘗試檢索自己,直到堆棧溢出。

創建一個私有變量來獲取和設置爲:

private string _CommandString; 
private string CommandString 
{ 
    //Also you probably want to change commandtype to value, since you will be 
    //discarding whatever you attempt to set the variable as 
    set { _CommandString = GetCommandString(commandtype); } 
    get { return _CommandString; } 
}