为什么必须写O AS INT而不能写(INT)O

Dim*_*zyr 4 c#

我在Jon Skeet的书中找到了一个使用as作为运算符的例子,它允许使用null值.

using System;

class A
{
    static void PrintValueAsInt32(object o)
    {
        int? nullable = o as int?; // can't write int? nullable = (int?)o
        Console.WriteLine(nullable.HasValue ?
                          nullable.Value.ToString() :
                          "null");
    }

    static void Main()
    {
        PrintValueAsInt32(5);
        PrintValueAsInt32("some string");
    }
}
Run Code Online (Sandbox Code Playgroud)

我无法理解,为什么我不能写int? nullable = (int?)o?当我尝试这样做时,我得到了一个例外.

Sel*_*enç 14

因为as operator在执行前检查.如果类型无法转换为对方那么它只是返回空值和避免InvalidCastException.

当您尝试执行显式转换时,您将获得异常,因为在第二个调用中,您将字符串传递给不可转换为int?

  • +1.为了完整起见,有一篇[来自Eric Lippert的好文章](http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and -cast-operators.aspx)更详细地解释了这些差异. (3认同)