欣赏有一些问题接近我要问的但不太像这里。我一直在检查?我和操作员遇到了以下情况。情况如下:
internal class Dog
{
public int? Age { get; set; }
}
主要代码检查如下:
Dog d2 = new Dog() { Age = 10 };
int age1 = d2.Age.Value; // compiles okay
int age2 = d2?.Age.Value; // CS0266
我想知道为什么age3的代码行正在请求显式转换。 d2.Age是int类型?和Age.Value属于int类型在两种用法之间没有变化。
答案 0 :(得分:2)
使用null-condicional运算符后,结果值可以是null
。这就是为什么它永远不会是int
。
您需要的是:
int age2 = (d2?.Age).Value;