C#可以将值类型与NULL进行比较我今天遇到了这种情况,不知道为什么C#编译器没有抛出错误。Int32 x = 1;if (x == null){
Console.WriteLine("What the?");}我搞不懂x怎么可能是空的。特别是由于此赋值肯定会引发编译器错误:Int32 x = null;是否有可能x会变成NULL,微软只是决定不把这个检查放入编译器中,还是完全错过了呢?更新:在修改了编写本文的代码之后,编译器突然想到了一个警告,即该表达式不可能为真。现在我真的迷路了。我将对象放入类中,现在警告已经消失,但留下了一个问题,值类型最终是否为NULL?public class Test{
public DateTime ADate = DateTime.Now;
public Test ()
{
Test test = new Test();
if (test.ADate == null)
{
Console.WriteLine("What the?");
}
}}
3 回答
不负相思意
TA贡献1777条经验 获得超10个赞
慕的地10843
TA贡献1785条经验 获得超8个赞
int?
表达式的结果总是‘false’,因为‘int’类型的值永远不等于‘int’类型的‘null’?
using System;struct MyValue{
private readonly int value;
public MyValue(int value) { this.value = value; }
public static bool operator ==(MyValue x, MyValue y) {
return x.value == y.value;
}
public static bool operator !=(MyValue x, MyValue y) {
return x.value != y.value;
}}class Program{
static void Main()
{
int i = 1;
MyValue v = new MyValue(1);
if (i == null) { Console.WriteLine("a"); } // warning
if (v == null) { Console.WriteLine("a"); } // no warning
}}MainMyValue(1)
.method private hidebysig static void Main() cil managed{
.entrypoint .maxstack 2
.locals init (
[0] int32 i,
[1] valuetype MyValue v)
L_0000: ldc.i4.1
L_0001: stloc.0
L_0002: ldloca.s v
L_0004: ldc.i4.1
L_0005: call instance void MyValue::.ctor(int32)
L_000a: ret
}private static void Main(){
MyValue v = new MyValue(1);}- 3 回答
- 0 关注
- 1449 浏览
添加回答
举报
0/150
提交
取消
