为什么'Convert.ToInt32'和'as int?'的工作方式不同?


Convert.ToInt32(myCommand.ExecuteScalar()); // Returns 100, because myCommand is a SQL command that gets a non-null BigInt cell
myCommand.ExecuteScalar() as int? ?? 0; //Returns 0 even when myCommand is SQL command that gets a non-null BigInt cell

在这种情况下,我必须使用第二种方式,因为myCommand.ExecuteScalar()可以返回DBNull。但是为什么第二种方法返回的结果与Convert.ToInt32不同呢?

编辑:谢谢大家。将类型更改为Int64,现在可以工作了

转换和强制转换(使用强制转换操作符,is操作符和as操作符)是两件不同的事情:

  • 转换将一种类型更改为另一种类型。比如从stringInt64Int32
  • 类型转换只能从基类型转换到继承类型。在本例中,从objectInt32object必须包含Int32才能成功。在你的情况下,它没有,强制转换将返回null
在代码:

Int64 l = 100;
object o = l;
Int32 i1 = o as Int32? ?? 0; // Cast fails, so "as" will return 0. "??" will make it 0.
Int32 i2 = Convert.ToInt32(o); // The Int32 inside the object will be converted into an Int32 and will return 100.

Convert.ToInt32调用传入对象的IConvertible接口。对于像doubleBigInteger这样的类型,这是实现的,并将对象转换为您期望的int

as关键字进行强制转换;如果强制转换失败,则返回null。这只会在对象已经是int的情况下起作用,而不仅仅是当它是一个可以转换为int的类型时。例如

double d = 1.0;
object o = d;
int? i1 = o as int?; // results in null
int i2 = (int)d; // works
int i3 = Convert.ToInt32(o); //works
int i4 = Convert.ToInt32(d); //works
int i5 = (int)o; // throws an exception at run time

最新更新