如何在 C# 中将值类型转换为 byte[]? [英] how to convert a value type to byte[] in C#?

查看:61
本文介绍了如何在 C# 中将值类型转换为 byte[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

byte[] byteArray;
enum commands : byte {one, two};
commands content = one;
byteArray = (byte*)&content;

是的,它现在是一个字节,但考虑到我将来想改变它吗?如何让 byteArray 包含内容?(我不想复制它).

yes, it's a byte now, but consider I want to change it in the future? how do I make byteArray contain content? (I don't care to copy it).

推荐答案

BitConverter 类可能正是您要找的.示例:

The BitConverter class might be what you are looking for. Example:

int input = 123;
byte[] output = BitConverter.GetBytes(input);

如果您的枚举已知是 Int32 派生类型,您可以简单地先转换其值:

If your enum was known to be an Int32 derived type, you could simply cast its values first:

BitConverter.GetBytes((int)commands.one);

这篇关于如何在 C# 中将值类型转换为 byte[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆