2012-07-31 28 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; 
    }