首页 文章

在C#中,Int64不等于long吗?

提问于
浏览
28

我一直在使用C#中的SQL和数据库来通过SqlCeConnection . 我一直在使用ExecuteReader读取记录ID的结果和BigInt值,这些记录ID被读入Longs .

今天我一直在玩SQL语句,这些语句使用基于COUNT的语句('SELECT COUNT(*) FROM X')并且一直在使用ExecuteScalar来读取这些单值结果 .

但是,我遇到了一个问题 . 我似乎无法将值存储到Long数据类型中,我一直在使用它 . 我可以将它们存储到Int64中 .

我一直在使用BigInt作为记录ID来获取最大可能的记录数 .

因此,BigInt 8字节是Int64 . 不是Long等于Int64,因为它们都是64位有符号整数?

因此,为什么我不能将Int64转换为Long?

long recordCount =0;

recordCount = (long)selectCommand.ExecuteScalar();

错误是:

指定的演员表无效 .

我可以将BigInt读成Long . 这不成问题 . 我无法读取SQL COUNT到long .

COUNT返回一个Int(Int32),所以问题实际上是将Int32转换为long .

2 回答

  • 5

    longInt64 in .NET;它只是C#中的别名 . 您的问题是将返回值转换为 long ,除非我们知道您的查询返回的类型,否则我们不知道您为什么会收到错误 . SQL BigInt必须可转换为 long .

    如果是返回的COUNT(*),那么它是Int32 . 您需要使用Convert类:

    long l = Convert.ToInt64(selectCommand.ExecuteScalar());
    
  • 28

    如果您认为您的计数将溢出int / Int32,则应该在SQL中使用COUNT_BIG() - 它具有正确的返回类型 .


    至于为什么演员不工作,我不确定 . 以下C#:

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    long lCount = (long)cmd.ExecuteScalar();
    Int64 iCount = (Int64)cmd.ExecuteScalar();
    

    编译到这个IL:

    L_0000: nop 
    L_0001: newobj instance void [System.Data]System.Data.SqlClient.SqlCommand::.ctor()
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
    L_000d: unbox.any int64
    L_0012: stloc.1 
    L_0013: ldloc.0 
    L_0014: callvirt instance object [System.Data]System.Data.Common.DbCommand::ExecuteScalar()
    L_0019: unbox.any int64
    L_001e: stloc.2 
    L_001f: ret
    

    也就是说,它们似乎编译成相同的代码 .

相关问题