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));
}
}
問:這是不重複執行代碼正確的策略?
你有你的假設,爲什麼不在調試器中測試它並得出結論? – MickyD
@MickyD感謝您的評論。我對VS還不是很熟悉。我不確定如何從調試器中得出任何結論:( – Vlastimil
你似乎試圖重塑['懶惰'](https://msdn.microsoft.com/en-us/library/dd642331(v = vs .1px).aspx)(儘管在這裏,用一個簡單的計算,它不一定值得做任何事情) –