public class B { public static implicit operator B(A values) { return null; } } public class A { } public class Program { static void Main(string[] args) { A a = new A(); B b = a ?? new B(); //b = null ... is it wrong that I expect b to be B() ? } }
此代码中的变量“b”被计算为null.我不明白为什么它是null.
我用Google搜索并在此问题中找到了回复 – Implicit casting of Null-Coalescing operator result – 与官方规范.
但是按照这个规范,我找不到“b”为空的原因:(也许我读错了,在这种情况下我为垃圾邮件道歉.
If A exists and is not a nullable type or a reference type,a compile-time error occurs.
……事实并非如此.
If b is a dynamic expression,the result type is dynamic. At run-time,a is first evaluated. If a is not null,a is converted to dynamic,and this becomes the result. Otherwise,b is evaluated,and this becomes the result.
……事实并非如此.
Otherwise,if A exists and is a nullable type and an implicit conversion exists from b to A0,the result type is A0. At run-time,a is unwrapped to type A0,b is evaluated and converted to type A0,and this becomes the result.
…存在,从b到A0的隐式转换不存在.
Otherwise,if A exists and an implicit conversion exists from b to A,the result type is A. At run-time,a becomes the result. Otherwise,b is evaluated and converted to type A,从b到A的隐式转换不存在.
Otherwise,if b has a type B and an implicit conversion exists from a to B,the result type is B. At run-time,a is unwrapped to type A0 (if A exists and is nullable) and converted to type B,b is evaluated and becomes the result.
… b有一个B型,从a到B存在隐式转换.
a被评估为null.因此,应评估b,结果应为b.Otherwise,a and b are incompatible,and a compile-time error occurs.
Does not happen我错过了什么吗?
解决方法
• Otherwise,if y has a type Y and an implicit conversion exists from x to Y,the result type is Y. At run-time,x is first evaluated. If x is not null,x is unwrapped to type X0 (if X exists and is nullable) and converted to type Y,y is evaluated and becomes the result.
有时候是这样的.首先,检查左侧x(仅为a)为空.但它本身并不是空的.然后使用左侧.然后运行隐式转换.它的类型B的结果是…… null.
请注意,这与以下内容不同:
A a = new A(); B b = (B)a ?? new B();
在这种情况下,左操作数是表达式(x),其本身为空,结果变为右侧(y).
也许引用类型之间的隐式转换应该返回null(if和)仅当原始为null时,作为一种好的做法?
我想那些编写规范的人可能会这样做(但没有):
• Otherwise,x is first evaluated and converted to type Y. If the output of that conversion is not null,that output becomes the result. Otherwise,y is evaluated and becomes the result.
也许那会更直观?无论转换的输入是否为null,它都会强制运行时调用隐式转换.如果典型的实现快速确定null→null,那应该不会太昂贵.