[英]Why should convert null value to nullable struct
I have a function which gives back a nullable struct
. 我有一个函数,它返回一个可为空的
struct
。 I noticed two similar cases 我注意到两个类似的案例
First: works well: 第一:效果很好:
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
if (size >= epsilon)
return null;
return new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true);
}
Second: needs to convert the null value to GeometricCircle? 第二:需要将null值转换为GeometricCircle吗?
public static GeometricCircle? CircleBySize(GeometricPoint point, double size)
{
return size > epsilon ? new GeometricCircle(point.Position, new Vector(1, 0, 0), size, true) : (GeometricCircle?)null;
}
Does anybody know what is the difference? 有人知道有什么区别吗?
In your first example, you are returning null
when size >= epsilon
. 在第一个示例中,当
size >= epsilon
时,返回null
。 The compiler knows that null
is a valid value for a nullable type. 编译器知道
null
是可空类型的有效值。
In your second example, you are using the ?:
ternary operator , which comes with its own set of rules. 在第二个示例中,您使用的是
?:
三元运算符 ,它带有自己的一组规则。
condition ? first_expression : second_expression;
MSDN tells us (my emphasis)... MSDN告诉我们(我的重点)......
Either the type of
first_expression
andsecond_expression
must be the same, or an implicit conversion must exist from one type to the other.first_expression
和second_expression
的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换 。
The key difference here is that null
cannot be implicitly converted into a GeometricCircle
, (the type of your first_expression
). 这里的关键区别是
null
不能隐式转换为GeometricCircle
( first_expression
的类型)。
So you have to do it explicity , using a cast to GeometricCircle?
所以你必须明确表达 ,使用一个转换为
GeometricCircle?
, which is then implicitly convertible to GeometricCircle
. ,然后可以隐式转换为
GeometricCircle
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.