哪个更有效率?使用是对象和/或尝试捕获

时间:2010-10-14 16:11:37

标签: c# asp.net try-catch

这是更有效/更好的代码。使用是对象,然后unbox如果它是那种类型的对象?或者使用try catch

WizardStep parentWizardStep;    
try
 {
   parentWizardStep = (WizardStep)this.Parent;
 }
catch
{
   throw new Exception("Unable to cast parent control to this type.");
}
  

或者这个:

WizardStep parentWizardStep;         
if(this.Parent is WizardStep) 
{ 
    parentWizardStep= (WizardStep)this.Parent; 
} 
else  
{  
    throw new Exception("Unable to cast parent control to this type."); 
}

2 个答案:

答案 0 :(得分:17)

如果您需要在演员表无效时抛出异常,为什么还要抓住正常的InvalidCastException?只需投射它就没有额外的代码:

WizardStep parentWizardStep = (WizardStep) Parent;

您目前正在替换一个异常,该异常在其类型(InvalidCastException - 至少,所以您希望)中传达其含义,只有Exception - 您为什么要丢失信息?

如果属于正确类型的相关值的错误,上面肯定是我经常做的。否则,使用as运算符和空检查:

WizardStep parentWizardStep = Parent as WizardStep;
if (parentWizardStep == null)
{
    // It wasn't a WizardStep. Handle appropriately
}
else
{
    // Use the WizardStep however you want
}

但无论如何,做一些你知道可能引发异常的东西是非常可怕的,并且很容易测试以避免异常,但选择抓住它。效率会很差,但更重要的是它只是不恰当地使用异常。除了其他任何东西,你现在正在捕捉所有异常......如果抓取this.Parent会引发一些完全不同的异常呢?它可能与铸造无关。除非您尝试实现某些顶级“全能”处理程序(例如,中止服务器请求),否则只捕获特定的异常。

答案 1 :(得分:5)

使用代替更有效:

WizardStep parentWizardStep = this.Parent as WizardStep;
if(parentWizardStep == null)
{
     // This isn't the right type
     throw new ApplicationException("Your exception here.");
}

// Use parentWizardStep here....
相关问题