Object
类型的变量中有一个值。Type
类型的变量。 Q值。我想得到表示这个值的字节数组。我正在尝试使用BitConverter.GetBytes
,但它需要一个类型变量。有没有办法让类型变量动态地具有值并在单独的变量中键入?
谢谢。
答案 0 :(得分:2)
如果你不想在每种类型上switch
并调用适当的方法,这是最快的方法,你可以使用反射,虽然有点慢:
byte[] GetBytes(object obj)
{
var type = obj.GetType();
return (byte[])typeof(BitConverter)
.GetMethods(BindingFlags.Public | BindingFlags.Static)
.Single(m => m.Name == "GetBytes" && m.GetParameters().Single().ParameterType == type)
.Invoke(null, new object[] { obj });
}
致电GetBytes((short)12345)
会产生new byte[] { 0x39 ,0x30 }
。
答案 1 :(得分:2)
public byte[] GetAnyBytes(dynamic myVariable) {
return BitConverter.GetBytes(myVariable)
}
dynamic
本质上是“我不知道这可能是什么类型,请在运行时检查”。显然,这比使用真实类型慢,但它更灵活。此外,还需要C#4.0。
答案 2 :(得分:1)
您可以尝试这样的方法来获取字节数组。
public static byte[] Object2ByteArray(object o)
{
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(ms, o);
return ms.ToArray();
}
}
虽然根据您的描述,您可能在其他地方做出了一些糟糕的实施选择。
找到here。
答案 3 :(得分:0)
我担心您尝试使用二进制格式与其他设备进行交互。假设您的数据接收方不是.NET,则数据类型的二进制表示形式因设备而异。我认为你最好在文本中表示这些信息,并使用解析器来解释文本。
答案 4 :(得分:0)
您可以使用MemoryMappedFile
private byte[] GetBytes<T>(T obj) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
using(var mmf = MemoryMappedFile.CreateNew("test", size))
using(var acc = mmf.CreateViewAccessor())
{
acc.Write(0, ref obj);
var arr = new byte[size];
for (int i = 0; i < size; i++)
arr[i] = acc.ReadByte(i);
return arr;
}
}