我正在寫一些代碼,並使用基於枚舉值的簡單switch語句。我想到在將來某個時候開發人員可能會添加一個新值,所以我在運行時包含了一個默認方法來捕獲這個值,並拋出一個異常。然而,我意識到每次放入這樣的邏輯時我都應該這樣做,並且我只會在運行時看到這些問題,而不是編譯時間。
我想知道是否有一些代碼可以讓編譯器告訴開發者在更新枚舉值時需要更新某些方法 - 而不僅僅是向枚舉本身添加註釋?C#確保有效的枚舉值 - 面向未來的方法
例如(下面的例子純粹是理論上的;我從開發生命週期中選擇狀態以確保它對大多數人來說都是熟悉的)。
public enum DevelopmentStatusEnum
{
Development
//, QA //this may be added at some point in the future (or any other status could be)
, SIT
, UAT
, Production
}
public class Example
{
public void ExampleMethod(DevelopmentStatusEnum status)
{
switch (status)
{
case DevelopmentStatusEnum.Development: DoSomething(); break;
case DevelopmentStatusEnum.SIT: DoSomething(); break;
case DevelopmentStatusEnum.UAT: DoSomething(); break;
case DevelopmentStatusEnum.Production: DoSomething(); break;
default: throw new StupidProgrammerException(); //I'd like the compiler to ensure that this line never runs, even if a programmer edits the values available to the enum, alerting the program to add a new case statement for the new enum value
}
}
public void DoSomething() { }
}
public class StupidProgrammerException: InvalidOperationException { }
這有點學術性,但我可以看到它有助於使我的應用程序健壯。有沒有人曾經嘗試過/有什麼好的想法可以實現?
由於提前,
JB
我這樣做就像你做的一樣。 –
每當你發現自己寫了一個switch語句,你應該考慮將代碼重構爲使用多態。 Martin Fowler的着作[Refactoring](http://martinfowler.com/books/refactoring.html)[見這個exerpt](http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism)。這將使您的代碼遵守開放原則(OCP),並幫助下一位開發人員避免錯過更改某處的switch語句。 :-) –