哪个代码更高效/更好。使用是对象,如果是该类型的对象,则打开框?或者使用尝试捕捉
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.");
}
发布于 2010-10-14 08:15:03
如果在强制转换无效时需要抛出异常,为什么要费心捕捉正常的InvalidCastException
?只需在没有额外代码的情况下抛出它:
WizardStep parentWizardStep = (WizardStep) Parent;
您目前正在用普通的InvalidCastException
替换以它的类型传递它的意义的异常(至少您希望如此)--为什么要丢失信息?
如果相关的值不是正确的类型,那么上面的内容肯定是我一直在做的。否则,使用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
会引发完全不同类型的异常怎么办?这可能与铸造无关。只捕获特定的异常,除非您试图实现一些顶级的“所有捕获”处理程序(例如中止服务器请求)。
发布于 2010-10-14 08:15:40
更有效的方法是使用作为:
WizardStep parentWizardStep = this.Parent as WizardStep;
if(parentWizardStep == null)
{
// This isn't the right type
throw new ApplicationException("Your exception here.");
}
// Use parentWizardStep here....
https://stackoverflow.com/questions/3935246
复制