我們希望避免產生NullReferenceException
。目前我們有:轉換時避免NullReferenceException的首選做法?
ISomeInterface interface = this.GetISomeInterfaceInstance();
(interface as ClassImplmentsISomeInterface).Method();
這工作正常,但風險NullReferenceException
。一個解決方案是:
ISomeInterface interface = this.GetISomeInterfaceInstance();
ClassImplmentsISomeInterface instance = interface as ClassImplmentsISomeInterface;
if (instance != null)
instance.Method();
但這會產生大量的額外的代碼爲一個簡單的檢查(根據ReSharper的有可能的NRE的100S)。第二溶液的方法是:
ISomeInterface interface = this.GetISomeInterfaceInstance();
if (interface is ClassImplmentsISomeInterface)
(interface as ClassImplmentsISomeInterface).Method();
但我知道is
實際上在後臺使用了as
,因此做了兩次演員,我想避免。這很重要嗎?例如,C#編譯器是否足夠聰明以優化此性能問題?
有沒有其他一些技術我在這裏失蹤?或者上述方法之一更可取?
如果代碼無法調用Method()方法, '?如果答案是否定的,那麼NRE可能是最好的事情發生。 – 2012-08-16 09:19:04
@Damien_The_Unbeliever在每個我們冒着NRE風險的情況下,我們可以在沒有調用Method()的情況下繼續 - 我們可以靜靜地登錄並繼續。如果不考慮這個問題,我不會問這樣一個具體的問題。 :) – 2012-08-16 10:16:42