即使在使用 is 运算符验证 C# 中的类类型之后,仍使用 as 运算符进行强制转换?
据我所知,使用 as
运算符通过显式强制转换来强制转换对象通常更可取,因为如果强制转换失败,引用变量将变为 null 而不是抛出异常。
但是,假设我在使用 as
运算符之前检查对象的类类型,该对象位于列表内部,就像这样,
DrawableGameComponent drawComponent;
foreach (component in Components)
{
if (component is DrawableGameComponent)
{
drawComponent = component as DrawableGameComponent;
// do something with drawComponent
}
}
使用 as
运算符首先使用 is
运算符进行检查会失去其优势吗?因此,执行以下转换同样好,因为我们在尝试转换之前首先使用 is
检查类类型?
if (component is DrawableGameComponent)
{
((DrawableGameComponent)componet).Visible = true;
}
我只是想知道我是否缺少一些基础部分,或者这是否真的取决于使用哪种模式的品味问题。后一种模式是否会通过显式强制转换产生垃圾?
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
更好(节省一个“转换” - 比较生成的 IL):
better (saves one "cast" - compare the generated IL):
您通过使用 as 运算符检查该类两次,尽管我怀疑开销是否会很明显,除非在真正的大规模循环中。
我更喜欢使用 as 并测试 null 并清理您的声明以减少行数:
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:
我会使用
FXCop 可以帮助挑选代码中可以从这样的小优化中受益的地方
I would use
FXCop can help picking up places in your code that can benefit from small optimisations like this
通过组合
is
和as
,您可以有效地进行两次类型检查。在这种情况下仅使用as
(如其他答案所示)即可获得您想要的结果,并产生更具可读性的代码(IMO)。By combining
is
andas
you're effectively doing the type checking twice. Just usingas
in this context (as the other answers show) gets you what you want, and results in more readable code IMO.您可以使用 LINQ 来获取您的类型。这样就不需要铸造了。
You can use LINQ just to get your types. This way no casting is required.