加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:03:46 所属栏目:百科 来源:网络整理
导读:我发现了我的程序的一个奇怪的行为,经过进一步的分析,我发现在我的C#知识或其他地方可能存在错误.我相信这是我的错,但我无法在任何地方找到答案…… public class B{ public static implicit operator B(A values) { return null; }}public class A { }publi
我发现了我的程序的一个奇怪的行为,经过进一步的分析,我发现在我的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,那应该不会太昂贵.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读