【发布时间】:2011-02-04 10:38:30
【问题描述】:
我正在使用发回图像的设备,当我请求图像时,图像数据之前会出现一些未记录的信息。我只能通过查看二进制数据并识别其中的图像头信息来实现这一点。
我原来有一个普通的方法,然后将它转换为扩展方法。这里的原始问题与编译器抱怨没有 Array 作为第一个参数(我有 Byte[])有关,但事实证明我犯了一个错误,忘记删除调用代码中的第一个参数。换句话说,我曾经有:
Byte[] new_buffer = RemoveUpToByteArray(buffer, new byte[] { 0x42, 0x4D });
改成扩展方法后,我误用了:
buffer.RemoveUpToByteArray( buffer, new byte[] { 0x42, 0x4D });
无论如何,现在这一切都已解决,因为我在将代码示例输入 SO 时意识到了自己的错误。 但是,我有一个新问题,就是对扩展方法和引用与值类型缺乏了解。代码如下:
public static void RemoveFromByteArrayUntil(this Byte[] array, Byte[] until)
{
Debug.Assert(until.Count() > 0);
int num_header_bytes = until.Count();
int header_start_pos = 0; // the position of the header bytes, defined by [until]
byte first_header_byte = until[0];
while(header_start_pos != -1) {
header_start_pos = Array.IndexOf(array, first_header_byte, header_start_pos);
if(header_start_pos == -1)
break;
// if we get here, then we've found the first header byte, and we need to look
// for the next ones sequentially
for(int header_ctr=1; header_ctr<num_header_bytes; header_ctr++) {
// we're going to loop over each of the header bytes, but will
// bail out of this loop if there isn't a match
if(array[header_start_pos + header_ctr] != until[header_ctr]) {
// no match, so bail out. but before doing that, advance
// header_start_pos so the outer loop won't find the same
// occurrence of the first header byte over and over again
header_start_pos++;
break;
}
}
// if we get here, we've found the header!
// create a new byte array of the new size
int new_size = array.Count() - header_start_pos;
byte[] output_array = new byte[new_size];
Array.Copy(array, header_start_pos, output_array, 0, new_size);
// here is my problem -- I want to change what array points to, but
// when this code returns, array goes back to its original value, which
// leads me to believe that the first argument is passed by value.
array = output_array;
return;
}
// if we get here, we didn't find a header, so throw an exception
throw new HeaderNotInByteArrayException();
}
我现在的问题是,扩展方法的第一个 this 参数似乎是按值传递的。我想重新分配数组指向的内容,但在这种情况下,我似乎只需要操作数组的数据。
【问题讨论】:
-
不是答案,只是观察:您的 RemoveUpToByteArray 似乎每次调用时都必须创建一个新的字节数组。使用整数作为数组的索引来跟踪您已阅读的距离会更有效。
-
@Dave:您对编译器错误发生的位置并不太具体。我猜它在 call site 而不是扩展方法。即使是这样,您也没有显示任何代码。您需要充实这一点才能得到答案,因为您可以在字节数组上创建扩展方法并轻松执行它们。
-
好的,没问题!我会继续发布 real 代码。 :) 感谢您的反馈。
-
@casperOne:实际上我写错了这个问题,我会在调用者和被调用者(扩展方法)中有错误。我会尽快发布所有内容。
-
您的扩展方法是否与调用代码具有相同的命名空间?如果没有,是否引用了该命名空间?
标签: c# extension-methods bytearray