我在 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");
}
}
我不明白,为什么我不能写int?可为空 = (int?)o
?当我尝试这样做时,出现异常。
最佳答案
因为 as operator
在 cast 之前执行检查。如果类型不能相互转换,则它只返回 null 并避免 InvalidCastException
。
当您尝试执行 explicit 强制转换时出现异常,因为在第二次调用中您将字符串传递给无法转换为 int?
的方法/p>
关于c# - 为什么一定要写O AS INT而不能写(INT)O,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23302752/