我知道使用 as
运算符来转换一个对象,而不是显式转换,通常更可取,因为如果转换失败,引用变量将变为 null 而不是抛出一个异常(exception)。
但是,假设我在使用 as
运算符之前检查对象的类类型,它在 List 内部,就像这样,
DrawableGameComponent drawComponent;
foreach (component in Components)
{
if (component is DrawableGameComponent)
{
drawComponent = component as DrawableGameComponent;
// do something with drawComponent
}
}
如果先检查 is
操作符,使用 as
操作符会失去好处吗?所以做下面的转换也一样好,因为我们在尝试转换之前首先使用 is
检查类类型?
if (component is DrawableGameComponent)
{
((DrawableGameComponent)componet).Visible = true;
}
我只是想知道我是否遗漏了一些基础部分,或者这是否真的归结为使用哪种模式的品味问题。后一种模式是否会通过显式转换产生垃圾?
提前致谢!
最佳答案
更好(节省一次“转换”——比较生成的 IL):
DrawableGameComponent drawComponent;
foreach (component in Components)
{
drawComponent = component as DrawableGameComponent;
if (drawComponent != null)
{
// do something with drawComponent
}
}
关于c# - 使用 as 运算符进行转换,即使在使用 is 运算符验证 C# 中的类类型之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6770052/