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#でバイト[]を読み取り専用で渡す方法はありますか? コピーは解決策ではありません。メモリを無駄にしたくありません (ファイルが非常に大きくなる可能性があるため)。パフォーマンスを覚えておいてください!

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

ただし、次のように を渡す方がよいでしょう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 に答える