4

想想下面的代码:

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[]?抄袭不是解决办法。我不想浪费内存(因为文件可能会变得非常大)。请牢记性能!

4

3 回答 3

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
     ...
}

但是,最好像这样传递 a Stream
这样,您根本不会将整个文件读入内存。

static int Main() {
     Stream file = File.OpenRead("anyfile");
     SomeMethod(file);
     ...
}
static void SomeMethod(Stream data) {
     byte b = data.ReadByte();       // only reading is allowed
     ...
}
于 2010-07-18T20:56:32.020 回答
5

我想这可能是你正在寻找的。

编译下面的代码,你会得到这个编译错误:Property or indexer 'Stack2.MyReadOnlyBytes.this[int]' cannot be assigned to -- it is read only

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]);
   }
}
于 2010-07-18T21:41:16.950 回答
2

我建议您在完成这项工作的层次结构中使用尽可能高的对象。在您的情况下,这将是IEnumerable<byte>

static int Main() 
{
     byte[] data = File.ReadAllBytes("anyfile");
     SomeMethod(data);
}

static void SomeMethod(IEnumerable<byte> data)
{
    byte b = data.ElementAt(0); 
    // Notice that the ElementAt extension method is sufficiently intelligent
    // to use the indexer in this case instead of creating an enumerator
}
于 2010-07-18T20:57:51.380 回答