我正在从 SQL Server 表中读取一行数据,其中一个列的类型是 tinyint。
我想将此值获取到一个 int 或 int32 变量中。
rdr.GetByte(j)
(byte) rdr.GetValue(j)
看起来这似乎是唯一的检索值的方法。但是怎样将结果转化为 int
变量呢?
我正在从 SQL Server 表中读取一行数据,其中一个列的类型是 tinyint。
我想将此值获取到一个 int 或 int32 变量中。
rdr.GetByte(j)
(byte) rdr.GetValue(j)
看起来这似乎是唯一的检索值的方法。但是怎样将结果转化为 int
变量呢?
int value = rdr.GetByte(j);
不需要进行显式转换,因为从 byte
到 int
是一种扩展转换(没有数据丢失的可能性)。
注:保留了原文中的HTML标签。
请查看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
)。BitConverter
用于处理字节数组(byte
),而不是单个字节(byte
)。 - Stephen Cleary将byte
赋值给int
是可以的:
int myInt = myByte;
但是,也许你在 IDataRecord.GetByte
内部遇到了异常,这种情况下,你应该检查你使用的索引是否真的指向了一个 tinyint
列。你可以检查从 GetValue
返回的类型。对于 tinyint
列,它应该是一个 byte
。
Trace.Assert(rdr.GetValue(j).GetType() == typeof(byte));
int myInt = rdr.GetByte(rdr.GetOrdinal(TheNameOfTheTinyintColumn))
我遇到了一个小问题,与编程有关。如果你有一个对象类型是 System.Byte
类型,你不能直接将其转换为 int。你必须先将其转换为 byte,然后再转换为 int。
public int Method(object myByte)
{
// will throw a cast exception
// var val = (int)myInt;
// will not throw a cast exception
var val = (int)((byte)myInt)
return val;
}
Method((byte)1);
int myInt = (int) rdr.GetByte(j);
int myInt = rdr.GetByte(j);
var myInt = (int) rdr.GetByte(j);
(int)rdr.GetByte(j)
int value = Convert.ToInt32(rdr.GetValue(j));
同时,它还提供了与使用 int 数据库列的向后兼容性。
byte
隐式转换为int
的操作。 - abatishchevint value = (int) rdr.GetByte(j)
和 int value = Convert.ToInt(rdrGetByte(j)) - jtbGetByte
内部。 - Jordãoj
不是一个byte
。尝试使用int value = Convert.ToInt(rdr.GetValue(j));
。 - Stephen Cleary