'as'关键字的用例

Joh*_*luk 6 c#

我想知道,在这种情况下你会使用C#的'as'关键字,而不是转换和检查异常?考虑这个例子:

Parent obj = new Child();

// Method 1:
try
{
    Child result1 = (Child)obj;
}
catch (InvalidCastException)
{
    // Handle failed cast
}

// Method 2:
if(obj is Child)
{
    Child result2 = obj as Child;
}
else
{
    // Handle failed cast
}
Run Code Online (Sandbox Code Playgroud)

据我所知,方法1和方法2都产生完全相同的结果.我知道,当它们失败时,as关键字将产生null,而一个转换将抛出一个ClassCastException,但对我而言,这似乎不足以让两个几乎相同的方式来转换对象.所以我想知道,为什么C#语言设计师会遇到添加'as'关键字的麻烦?

Dan*_*ite 3

异常可能代价高昂并且具有隐式goto行为。

我会像这样执行案例 2,这样您就可以节省一些说明和清晰度。

Child result2 = obj as Child;
if(result2 != null)
{

}
else
{
    // Handle failed cast
}
Run Code Online (Sandbox Code Playgroud)