刚刚写行代码,傻到
DBAccess.GetCustomerID(del) = 0 ? MessageBox.Show("用户" + txtName.Text.Trim() + "删除成功") : MessageBox.Show("用户" + txtName.Text.Trim() + "删除失败");
的直接用下面的代码,编译的时候报错说:Error 1 Constant value '0' cannot be converted to a 'bool' D:\Users\Nokia\Documents\Visual Studio 2008\Projects\HJSTEEL\HJSTEEL\AddCustomerForm.cs 199 43 HJSTEEL
很不理解,于是和两哥们讨论了一下,他们给的方案是强制转换,结果同样报错。(杯具啊,三个写代码的居然连这点基础知识都忘记了);
于是,发现下面这样是可以的。
int a = 1;
bool b = Convert.ToBoolean(a);
Console.WriteLine(b);
bool b = Convert.ToBoolean(a);
Console.WriteLine(b);
但是很好奇Convert.ToBoolean()方法到底是怎么实现的,它有多个重载,string啊,object啊等等。于是使用IL DASM以为能看到点东西,结果只看到下面这些,也是直接调用Convet方法的。
.method private hidebysig instance void Test() cil managed
{
// Code size 18 (0x12)
.maxstack 1
.locals init ([0] int32 a,
[1] bool b)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call bool [mscorlib]System.Convert::ToBoolean(int32)
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: call void [mscorlib]System.Console::WriteLine(bool)
IL_0010: nop
IL_0011: ret
} // end of method Program::Test
{
// Code size 18 (0x12)
.maxstack 1
.locals init ([0] int32 a,
[1] bool b)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: stloc.0
IL_0003: ldloc.0
IL_0004: call bool [mscorlib]System.Convert::ToBoolean(int32)
IL_0009: stloc.1
IL_000a: ldloc.1
IL_000b: call void [mscorlib]System.Console::WriteLine(bool)
IL_0010: nop
IL_0011: ret
} // end of method Program::Test
好吧,还是用Reflactor,直接上代码:
public static bool ToBoolean(int value)
{
return (value != 0);
}
{
return (value != 0);
}
唉,原来Convert.ToBoolean(int value)的实现也就是比较啊。
虽然小题大做,但是弄明白弄清楚了。