c# - 什么时候应该在 C# 中使用 as 关键字

标签 c# .net c#-3.0 as-operator

大多数情况下,当您想要更改类型时,您只想使用传统的强制转换。

var value = (string)dictionary[key];

这很好,因为:

  • 速度很快
  • 如果出现问题它会提示(而不是给出 object is null 异常)

那么什么是使用 as 的好例子?我真的找不到或想不出适合它的东西?

注意:实际上,我认为有时编译器会阻止使用 as 有效的强制转换(与泛型相关?)。

最佳答案

有效对象不是您想要的类型时,使用as,如果是,您希望采取不同的行动。例如,在某种伪代码中:

foreach (Control control in foo)
{
    // Do something with every control...

    ContainerControl container = control as ContainerControl;
    if (container != null)
    {
        ApplyToChildren(container);
    }
}

或者 LINQ to Objects 中的优化(很多这样的例子):

public static int Count<T>(this IEnumerable<T> source)
{
    IList list = source as IList;
    if (list != null)
    {
        return list.Count;
    }
    IList<T> genericList = source as IList<T>;
    if (genericList != null)
    {
        return genericList.Count;
    }

    // Okay, we'll do things the slow way...
    int result = 0;
    using (var iterator = source.GetEnumerator())
    {
        while (iterator.MoveNext())
        {
            result++;
        }
    }
    return result;
}

所以使用 as 就像 is + 强制转换。根据上述示例,它几乎总是之后与无效检查一起使用。

关于c# - 什么时候应该在 C# 中使用 as 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7566212/

相关文章:

c# - 通过 ref 和没有 ref 传递的引用类型

c# - 在 Visual Studio 2015 中重命名时导致 "unresolvable conflict(s)"的原因是什么?

.net - 解决 MSB3247 - 发现同一依赖程序集的不同版本之间存在冲突

c# - 在 Button_Click 上围绕控件绘制边框

c# - 使用作为另一个列表的属性过滤对象列表。使用 linq

c# - 如何将 .NET exe 转换为 native Win32 exe?

c# - 有没有一种方法可以使正在运行的方法通过 cts.Cancel(); 立即停止?

c# - WCF Web 服务错误 : "Service endpoint binding not using HTTP protocol"?

C# 可变长度 args,哪个更好,为什么是 : __arglist, params 数组或 Dictionary<T,K>?

c# - 是否可以对第一个参数使用类型推断并指定另一种类型