如何只读一个字节数组?

rai*_*syn 2 c# bytearray readonly readonly-collection

考虑以下代码:

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
     ...
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在C#中只读传递byte []?复制不是解决方案.我不想浪费内存(因为文件可能会变得非常大).请记住表现!

SLa*_*aks 12

你可以传递一个ReadOnlyCollection<byte>,像这样:

static int Main() {
     byte[] data = File.ReadAllBytes("anyfile");
     SomeMethod(new ReadOnlyCollection<byte>(data));
     ...
}
static void SomeMethod(ReadOnlyCollection<byte> data) {
     byte b = data[0];       // only reading is allowed
     ...
}
Run Code Online (Sandbox Code Playgroud)

但是,最好传递一个Stream,就像这样:
这样,你根本不会将整个文件读入内存.

static int Main() {
     Stream file = File.OpenRead("anyfile");
     SomeMethod(file);
     ...
}
static void SomeMethod(Stream data) {
     byte b = data.ReadByte();       // only reading is allowed
     ...
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我想这可能就是你要找的。

编译下面的代码,你会得到这个编译错误:属性或索引器'Stack2.MyReadOnlyBytes.this[int]'不能被分配给——它是只读的

public class MyReadOnlyBytes
{
   private byte[] myData;

   public MyReadOnlyBytes(byte[] data)
   {
      myData = data;
   }

   public byte this[int i]
   {
      get
      {
         return myData[i];
      }
   }
}

class Program
{
   static void Main(string[] args)
   {
      var b = File.ReadAllBytes(@"C:\Windows\explorer.exe");
      var myb = new MyReadOnlyBytes(b);

      Test(myb);

      Console.ReadLine();
   }

   private static void Test(MyReadOnlyBytes myb)
   {
      Console.WriteLine(myb[0]);
      myb[0] = myb[1];
      Console.WriteLine(myb[0]);
   }
}
Run Code Online (Sandbox Code Playgroud)