2012-07-31 24 views
0

我用下面的代码连接两个byte[]使用覆盖运算符+
但有一个我不明白的错误。
这里是我的方法的头球覆盖运算符来连接两个字节数组

public static byte[] operator +(byte[] bytaArray1, byte[] bytaArray2){...} 

错误文本:

一个二元运算符的参数必须是包含类型

我应该如何实现呢?

+0

注意:如果你正在做大量的这个,它表明你应该可能是使用类似'MemoryStream'的东西,而不是 – 2012-07-31 06:40:14

回答

4

您无法为另一个类定义运算符。

一个替代方案是创建一个扩展方法像这样:

public static byte[] AddTo(this byte[] bytaArray1, byte[] bytaArray2){...} 
+0

我被通过了。但现在我确信我不能那样做。也不能使用'public static byte [] operator +(this byte [] b1,byte [] b2){return null; }' – Rzassar 2012-07-31 06:42:13

+0

我更喜欢这个解决方案:''public static byte [] concatByteArray(params byte [] [] p) { int sum = 0; byte [] tmp; foreach(p中的字节[]项) { sum + = item.Length; } tmp = new byte [sum] sum = 0; foreach(byte [] p项) Array.Copy(item,0,tmp,sum,item.Length); sum + = item.Length; } return tmp; }'' – raiserle 2016-06-09 07:30:29

0

这是因为您正试图在不是byte的类定义中创建运算符超载。

想这

class Program 
{ 
public static Program operator +(Program opleft, Program opright) 
{ 
    return new Program(); 
} 
} 

编译没有问题,因为我重载operator +方案和操作数我上我表演+操作类的节目了。

+1

好吧,为了更准确,这是因为运算符重载不在类byte []内。而且由于一个班级不能有'[]'作为其名字的一部分,Rzassar所要求的实际上是不可能的。 – 2012-07-31 06:35:50

0

我更喜欢这样的解决方案:

public static byte[] concatByteArray(params byte[][] p) 
    { 
     int newLength = 0; 
     byte[] tmp; 

     foreach (byte[] item in p) 
     { 
      newLength += item.Length; 
     } 

     tmp = new byte[newLength]; 
     newLength = 0; 

     foreach (byte[] item in p) 
     { 
      Array.Copy(item, 0, tmp, newLength, item.Length); 
      newLength += item.Length; 
     } 
     return tmp; 
    }