铸造空不编译 [英] Casting null doesn't compile

查看:168
本文介绍了铸造空不编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不小心在工作中我写了下面一行code:

accidentally at work I wrote the following line of code:

string x = (object) null; 
// It was var x = (object)null and I changed from var to string instead of 
// object x = null;

这给了我一个类似的编译错误:无法施展源类型的对象到目标字符串类型

This gave me a compilation error similar to this: Can't cast source type object to target type string

为什么呢?是不是只是一堆零指向无门的内存地址,不管是什么类型是?

Why? Isn't null just a bunch of zeros pointing to "nowhere" memory address, no matter what the type is?

推荐答案

这里的问题基本上是为什么编译器没有考虑到它知道所分配的值是一个常量引用称为是空的事实?

The question here is basically "why does the compiler not take into account the fact that it knows that the assigned value is a constant reference known to be null?"

答案是:何必呢?什么是服用这些信息考虑了诱人的好处?你故意说:我希望这个EX pression来对待,就好像是类型的对象,并可以object类型的值类型的字符串变量不分配。什么是允许,在这种情况下,有什么好处?

The answer is: why should it? What's the compelling benefit of taking that information into account? You deliberately said "I want this expression to be treated as though it were of type object", and you can't assign a value of type object to a variable of type string. What's the benefit of allowing that in this case?

在code在我看来是极有可能是一个错误;当然,编译器应该告诉你这件事,而不是允许它。

The code seems to me to be highly likely to be a bug; surely the compiler should be telling you about it rather than allowing it.

这篇关于铸造空不编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆