开发者

Should I prefer the 'is' or 'as' operator? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

casting vs using the 'as' keyword in the CLR

foreach (MyClass i in x)
{
        if (i is IMy)
        {
                IMy a =开发者_运维知识库 (IMy)i;
                a.M1();
        }
}

or

foreach (MyClass i in x)
{
        IMy a = i as IMy;
        if (a != null)
        {
                a.M1();
        }

}


Second is more preferable as you cast 1 time


I prefer a third option:

foreach(var i in x.OfType<IMy>()) {
    i.M1();
}


The second, as that only does one cast. Or you can use the OfType method:

foreach (IMy i in x.OfType<IMy>()) {
  i.M1();
}


Second is preferable, as you're casting only once.

This article can also help understand this. 'as' operation does the 'is' check and returns either a casted object or a null - does all the work for you.


The second. It's the same number of lines of code but you avoid doing the cast twice.

Note that whilst the second is preferable it wouldn't have worked it the type had been a value type. You can only use as on reference or nullable types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜