本文介绍了空条件运算符与可空类型的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一段代码在C#6和一些奇怪的原因这个作品

I'm writing a piece of code in c#6 and for some strange reason this works

var value = objectThatMayBeNull?.property;



但这并不:

but this doesn't:

int value = nullableInt?.Value;



如果不工作我的意思是,我得到一个编译错误说无法解析符号值
任何想法,为什么空条件运算符不工作?

推荐答案

好吧,我已经做了一些思考和测试。这是发生了什么:

Okay, I have done some thinking and testing. This is what happens:

int value = nullableInt?.Value;



编译时给出了这样的错误消息:

Gives this error message when compiling:

键入'诠释'不包含'值'

这意味着'转换'的 INT?进入实际 INT 值。这实际上是一样的:

That means that ? 'converts' the int? into the actual int value. This is effectively the same as:

int value = nullableInt ?? default(int);



其结果是一个整数,它不具有,效果显着。

好吧,可能这种帮助?

int value = nullableInt?;

没有,这种语法是不允许的。

No, that syntax isn't allowed.

那么是什么呢?只要保持使用 .GetValueOrDefault()这种情况。

So what then? Just keep using .GetValueOrDefault() for this case.

int value = nullableInt.GetValueOrDefault();

这篇关于空条件运算符与可空类型的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:47
查看更多