2015-10-06 53 views
3

我有以下代碼:StackOverflow的異常get和set

namespace QuantStrats 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string FilePath = "C:\\Users\\files\\DJ.csv"; 
      StreamReader streamReader = new StreamReader(FilePath); 
      string line; 
      List<Data> Data = new List<Data>();  

      while ((line = streamReader.ReadLine()) != null) 
      { 
       Data Tick = new Data(); 
       string [] values = line.Split(','); 
       Tick.SetFields(values[1], values[2]); 
       Data.Add(Tick); 
      } 

      for (int ii = 0; ii < Data.Count; ii++) 
      { 
       Data TickDataValues = new Data(); 
       TickDataValues = Data[ii];    
       Console.Write("TIME :" + TickDataValues.time + " Price : " + TickDataValues.price + Environment.NewLine); 
      } 

      Console.ReadLine(); 
     } 
    } 

    class Data 
    { 
     public DateTime time 
     { 
      get { return this.time; } 
      set 
      { 
       this.time = value;     
      } 
     } 

     public double price 
     { 
      get { return this.price; } 
      set 
      { 
       this.price = value;     
      } 
     } 

     public void SetFields(string dateTimeValue, string PriceValue) 
     { 
      try 
      { 
       this.time = Convert.ToDateTime(dateTimeValue); 
      } 
      catch 
      { 
       Console.WriteLine("DateTimeFailed " + dateTimeValue + Environment.NewLine); 
      } 

      try 
      { 
       this.price = Convert.ToDouble(PriceValue); 
      } 
      catch 
      { 
       Console.WriteLine("PriceFailed " + PriceValue + Environment.NewLine); 
      } 
     } 
    } 
} 

但我得到一個堆棧溢出異常。

我知道這是因爲我沒有做我的get和設置正確,我正在進入一個無限循環,但我不明白爲什麼會發生這種情況?

回答

7
public DateTime time 
{ 
    get { return this.time; } 
    set 
    { 
     this.time = value;     
    } 
} 

您不使用後備字段,而是在屬性設置器中設置屬性本身。

可以使用1固定這一點)自動屬性

public DateTime Time { get; set; } 

或2)背場

private DateTime _time; 
public Datetime Time 
{ 
    get { return _time; } 
    set { _time = value; } 
} 

它們都等同於相同的代碼。

有關說明,當你在你的代碼time

get { return this.time; } 

它具有檢索的time的價值迴歸。它是通過調用timeget,其中有獲得檢索time值等

+1

備份*字段*,不支持屬性。 –

+0

是的,謝謝@JonSkeet,努力成爲第一名,打字速度過快 – Jonesopolis

+1

絕對是#1的首選,除非您在設置/獲取屬性時需要額外的驗證或其他邏輯。 –

2

我不明白到底爲什麼發生這種情況?

public double price 
    { 
     get { return this.price; } 
     set 
     { 
      this.price = value;     
     } 
    } 

當你 「獲得」 price,爲price吸氣劑被調用,這就要求price的getter,它調用getter方法price,這...

只需使用自動實現性能,如果你不想惹支持字段:

public DateTime Time {get; set;} 
    public double Price {get; set;} 

其他一些意見:

  1. 屬性名稱的標準約定是以大寫字母開頭,這就是我在示例中將屬性更改爲TimePrice的原因。

  2. 你可能要考慮使用decimalPrice的屬性,如果你做任何浮點運算,因爲double有一些輕微的不精確性表示十進制數的1.1一樣的時候。 decimal將存儲數字exacly沒有任何精度損失。

  3. 只寫入控制檯的catch塊看起來不正確。你基本上忽略了錯誤(從邏輯流程的角度來看)。與其接受班級中的字符串並解析它們,我會在中調用代碼進行驗證,並在將它們傳遞給班級之前確保輸入有效。

1

屬性getter和setter方法實際上只是getXXXsetXXX方法(這是他們是如何編譯)。因爲你從屬性本身設置屬性,這是如果你在一個方法上無止境地重複出現。

public DateTime time() 
{ 
    return time(); 
} 

正如其他的答案所述,您可以使用支持字段或自動實現的屬性。