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

Som*_*per 2 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.");
}
Run Code Online (Sandbox Code Playgroud)

或这个:

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

Jon*_*eet 17

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

WizardStep parentWizardStep = (WizardStep) Parent;
Run Code Online (Sandbox Code Playgroud)

你现在正在替换一个异常,它在其类型中传达了它的意义(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
}
Run Code Online (Sandbox Code Playgroud)

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


Ree*_*sey 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....
Run Code Online (Sandbox Code Playgroud)