c# – 使用null-coalescing运算符进行隐式转换

前端之家收集整理的这篇文章主要介绍了c# – 使用null-coalescing运算符进行隐式转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现了我的程序的一个奇怪的行为,经过进一步的分析,我发现在我的C#知识或其他地方可能存在错误.我相信这是我的错,但我无法在任何地方找到答案……
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

我错过了什么吗?

解决方法

嗯,规范说(我改为x和y,以减少混淆):

• 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,那应该不会太昂贵.

原文链接:https://www.f2er.com/csharp/97411.html

猜你在找的C#相关文章