为什么编译器决定2.3是double,所以这段代码不能编译:
decimal x;
x = 2.3; // Compilation error - can not convert double to decimal.
x = (decimal) 2.3 // O.k.
Run Code Online (Sandbox Code Playgroud)
为什么编译器不这样想:
他想得到一个小数,他给我一个可以是十进制的值,所以它是十进制的!
为什么这不会出现编译错误:
short x;
x = 23; // O.K.
Run Code Online (Sandbox Code Playgroud)
谁说23不是int?
我不小心在工作中写了以下代码:
string x = (object) null;
// It was var x = (object)null and I changed from var to string instead of
// object x = null;
Run Code Online (Sandbox Code Playgroud)
这给了我一个与此类似的编译错误: Can't cast source type object to target type string
为什么?不null只是一堆零指向"无处"的内存地址,无论类型是什么?
这个问题再次引起了我的兴趣.有人可以提供技术解释,说明为什么以下代码不会产生任何警告或错误.你必须问自己的问题(当然)你感到幸运吗?
class Program
{
static string Feeling(object o) { return "Lucky"; }
static string Feeling(string s) { return "Unlucky"; }
static void Main(string[] args)
{
Console.WriteLine("I feel " + Feeling(null));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您知道在不运行代码的情况下将调用哪种方法,则会获得奖励积分.只是为了添加侮辱,它不仅仅发生在null参数:
class Program
{
static string Feeling(int i) { return "Lucky"; }
static string Feeling(uint i) { return "Unlucky"; }
static void Main(string[] args)
{
Console.WriteLine("I feel " + Feeling(7));
}
}
Run Code Online (Sandbox Code Playgroud) 以下程序将无法编译:
class Program
{
static void Main(string[] args)
{
int x = 50;
Byte[] y = new Byte[3] { x, x, x };
}
}
Run Code Online (Sandbox Code Playgroud)
毫不奇怪,我会得到错误 Cannot implicitly convert type 'int' to 'byte'
但是,如果我创建x一个const,那么它将编译:
class Program
{
public const int x = 50;
static void Main(string[] args)
{
Byte[] y = new Byte[3] { x, x, x };
}
}
Run Code Online (Sandbox Code Playgroud)
我很好奇这里发生了什么.如果一个int不能被隐式地转换为一个字节,编译器是否会动态创建我的const的"字节"版本,或者它是否编译它就好像我已经进行了显式转换,因为它认为常量值是"安全的"一个字节?也许编译器将其解释为我写的:
Byte[] y = new Byte[3] { 50, 50, 50 };
Run Code Online (Sandbox Code Playgroud)
因为这是合法的,所以我对编译器在这里所做的事情更感兴趣.
我在C++和C#中遇到了关于uint使用的几个类似的怪癖,现在我想知道推理(对于每个例子可能完全不同).对于这两个示例,请注意我正在编译时将警告级别设置为最大值.
(1)gcc抱怨在下面将int与uint进行比较,而vc ++没有:
uint foo = <somevalue>;
if( foo == ~0 ) //right here
...
Run Code Online (Sandbox Code Playgroud)
比较0就好了,没有任何强制转换gcc和vc ++.
(2)在C#3.5中,我遇到了一个类似的问题.以下工作正常:
uint foo = 1;
uint bar = 2;
Run Code Online (Sandbox Code Playgroud)
但这会给出一个uint/int警告:
bool condition = <somevalue>;
uint foo = condition ? 1 : 2; //right here
Run Code Online (Sandbox Code Playgroud)
是什么给出了,为什么编译器对立即值的签名如此敏感?我完全理解从变量赋值时的问题,但这对我来说对于直接值是没有意义的; 在解析中是否存在一些隐藏的难以阻止此行为被允许?或者是什么?
编辑:是的,我知道我可以用'你'来填充我的数字,但是这可以回避我的问题,即隐含地向左侧投射,而不是明确地施放右侧.