如何只读传递字节数组?
考虑以下代码:
static int Main() {
byte[] data = File.ReadAllBytes("anyfile");
SomeMethod(data);
...
}
static void SomeMethod(byte[] data) {
data[0] = anybytevalue; // this line should not be possible!!!
byte b = data[0]; // only reading should be allowed
...
}
在 C# 中是否有一种只读传递 byte[] 的方法?复制不是解决办法。我不想浪费内存(因为文件可能会变得很大)。请牢记性能!
Think of the following code:
static int Main() {
byte[] data = File.ReadAllBytes("anyfile");
SomeMethod(data);
...
}
static void SomeMethod(byte[] data) {
data[0] = anybytevalue; // this line should not be possible!!!
byte b = data[0]; // only reading should be allowed
...
}
Is there a way of readonly passing the byte[] in C#? Copying isn't a solution. I would not like to waste memory (because the file might get very big). Please keep performance in mind!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以传递
ReadOnlyCollection
,像这样:但是,最好传递
流
,如下所示:这样,您根本就不会将整个文件读入内存。
You can pass a
ReadOnlyCollection<byte>
, like this:However, it would be better to pass a
Stream
, like this:This way, you won't read the entire file into memory at all.
我想这可能就是您正在寻找的。
编译下面的代码,您将收到此编译错误:属性或索引器'Stack2.MyReadOnlyBytes.this[int]'无法分配给--它是只读的
I think this might be what you're looking for.
Compile the code below and you will get this compile error: Property or indexer 'Stack2.MyReadOnlyBytes.this[int]' cannot be assigned to -- it is read only
我建议您使用层次结构中尽可能最高的对象来完成这项工作。在您的情况下,这将是
IEnumerable
:I would recommend you using the highest possible object in the hierarchy that does the job. In your case this would be
IEnumerable<byte>
: