2017-10-19 14 views
0

IDE:的Visual Studio 2015年更新3C#代碼的有效性 - 調用屬性十倍

語言: C#/。NET 4.5

情況:假設我定義的類和我調用它的屬性數十次,進一步讓我們假設這個類對構造函數的一個輸入進行操作,因此它使得除第一個之外的所有操作都是多餘的,因爲我們已經設法在第一次調用它時計算返回值。這些財產的

例子:

// let's call it a Month, because it extracts a month code from a string 
private int Month 
{ 
    // there is only a getter 
    get 
    { 
     // here's my current strategy 
     // in the beginning of the class I set fMonth to -1 
     // it can only have possitive numbers, so if already set, I return it 
     if (fMonth > -1) 
      return fMonth; 

     // and here's the part I don't want to repeat 
     return fMonth = 
      Convert.ToInt32(SomeNumberString.Substring(2, 2)); 
    } 
} 

問:這是不重複執行代碼正確的策略?

+0

你有你的假設,爲什麼不在調試器中測試它並得出結論? – MickyD

+0

@MickyD感謝您的評論。我對VS還不是很熟悉。我不確定如何從調試器中得出任何結論:( – Vlastimil

+0

你似乎試圖重塑['懶惰'](https://msdn.microsoft.com/en-us/library/dd642331(v = vs .1px).aspx)(儘管在這裏,用一個簡單的計算,它不一定值得做任何事情) –

回答

1

您正在使用私人支持字段fmonth作爲屬性的正確方向。您可以通過將轉換代碼移到明確的設置方法來進一步優化。這將從每個獲取訪問中刪除if檢查。

ctor(string someNumberString) { 
    SetMonth(someNumberString); 
} 

private int Month { get { return fmonth; } } 
// -1 indicates that SetMonth() has never been called 
private int fmonth = -1; 

public void SetMonth(string someNumberString) { 
    fmonth = Convert.ToInt32(someNumberString.Substring(2, 2)); 
} 
2

由於在構造函數中給出了someNumberString的值,所以可以使用只讀屬性。

ctor(string someNumberString) 
{ 
    Month = Convert.ToInt32(someNumberString.Substring(2, 2)); 
} 

public Month { get; }