Using as operator to cast, even after using is operator to verify class type in C#?
I understand that using the as
operator to cast an object, over an explicit cast, is usually more desirable due to the fact that if the cast fails, the reference variable goes to null instead of throwing an exception.
However, lets say I check to see the type of class an object is, that's inside of a List, prior using the as
operator, like so,
DrawableGameComponent drawComponent;
foreach (component in Components)
{
if (component is DrawableGameComponent)
{
drawComponent = component as DrawableGameComponent;
// do something with drawComponent
}
}
does using the as
operator lose its benefits by checking with the is
operator first? So doing the following cast is just as good, because we first check the class type using is
before attempting the cast?
if (component is DrawableGameComponent)
{
((DrawableGameComponent)componet).Visible = true;
}
I'm just wondering if there is开发者_高级运维 some underlying piece I'm missing, or if this truly comes down to a matter of taste which pattern to use. Does the latter pattern create garbage through the explicit cast?
Thanks in advance!
better (saves one "cast" - compare the generated IL):
DrawableGameComponent drawComponent;
foreach (component in Components)
{
drawComponent = component as DrawableGameComponent;
if (drawComponent != null)
{
// do something with drawComponent
}
}
You're checking the class twice by using the as operator, although I doubt the overhead would be noticeable unless in a truly massive loop.
I much prefer using as and testing for null and also cleaning up your declaration for even fewer lines:
foreach (component in Components)
{
var drawComponent = component as DrawableGameComponent;
if (drawComponent != null)
{
// do something with drawComponent
}
}
I would use
DrawableGameComponent drawComponent;
foreach (component in Components)
{
drawComponent = component as DrawableGameComponent;
if (drawComponent != null)
{
// do something with drawComponent
}
}
FXCop can help picking up places in your code that can benefit from small optimisations like this
By combining is
and as
you're effectively doing the type checking twice. Just using as
in this context (as the other answers show) gets you what you want, and results in more readable code IMO.
You can use LINQ just to get your types. This way no casting is required.
public class A
{
}
public class B : A
{
public bool Visible { get; set; }
}
public class C : A
{
}
void Main()
{
var data = new List<A> { new A(), new B(), new C(), new B() };
data.OfType<B>().ToList().ForEach(x => x.Visible = true);
}
精彩评论