c# - 使用 as 运算符进行转换,即使在使用 is 运算符验证 C# 中的类类型之后?

标签 c# .net casting xna type-conversion

我知道使用 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/

相关文章:

c# - 我能否使用 Moq 来验证是否使用复杂参数中的特定值调用了模拟方法?

c# - 为什么此 WCF 代理代码有效?

.net - 我应该将敏感数据传递给 .NET 中的 Process.Start 调用吗?

c# - 无法从 ObservableCollection<string> 转换为 ObservableCollection`1<string>

c# - 在 C# 并行任务中为多个服务调用创建并行任务

c++ - 通过转换为 Visual C++ 中的函数指针来执行 shellcode

Java "x += y"和 "x = x+y"产生不同的结果

angular - 如何在 Angular 2+ 中将 md ElementRef 转换为 HtmlElement

c# - 从 System.Collections.Generic.List c# 中选择 x 个元素

c# - Environment.StackTrace 如何抛出 ArgumentOutOfRangeException?