繁体   English   中英

字节到C#中的整数

[英]Byte to integer in C#

我正在从SQL Server表中读取一行。 列之一是tinyint类型。

我想将值转换为int或int32变量。

rdr.GetByte(j)
(byte) rdr.GetValue(j)

...似乎是检索值的唯一方法。 但是,如何将结果转换为int变量?

int value = rdr.GetByte(j);

不需要显式强制转换,因为将byte转换为int会扩大转换范围(不会丢失数据)。

请参阅BitConverter.ToInt32的文档(包含更多示例):

byte[] bytes = { 0, 0, 0, 25 };

// If the system architecture is little-endian (that is, little end first),
// reverse the byte array.
if (BitConverter.IsLittleEndian)
    Array.Reverse(bytes);

int i = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int: {0}", i);
// Output: int: 25

byte分配给int可以工作:

int myInt = myByte;

IDataRecord.GetByte , in which case you should check that the index you're using to access the data record really points to a tinyint column. 但是,也许您 IDataRecord.GetByte 遇到了异常,在这种情况下,您应该检查用于访问数据记录的索引是否确实指向tinyint列。 您可以检查从GetValue返回的类型。 对于tinyint列,它应该是一个byte

Trace.Assert(rdr.GetValue(j).GetType() == typeof(byte));

另一个选择是完全放弃脆弱的数字索引:

int myInt = rdr.GetByte(rdr.GetOrdinal(TheNameOfTheTinyintColumn))

将字节转换为int应该可以正常工作:

int myInt = (int) rdr.GetByte(j);

由于C#支持从byte到int的隐式转换 ,因此您可以选择执行以下操作:

int myInt = rdr.GetByte(j);

您选择哪种选择取决于您的偏好(是否要记录是否进行了强制转换的事实)。 请注意,如果要使用类型推断 ,则将需要显式转换,否则myInt将具有错误的类型:

var myInt = (int) rdr.GetByte(j);
(int)rdr.GetByte(j)

这类似于Stephen Cleary对已接受答案的评论,但是我需要指定int的大小。 这为我工作:

int value = Convert.ToInt32(rdr.GetValue(j));

(并且它还提供了与使用int的数据库列的向后兼容性。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM