简体   繁体   English

覆盖运算符以连接两个字节数组

[英]overriding operator to concat two byte array

i used the following code to concatenate two byte[] using override operator + . 我使用以下代码使用覆盖运算符+连接两个byte[]
but there is an error i cannot understand. 但是有一个我无法理解的错误。
here is my method's header 这是我方法的标题

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

Error text: 错误文字:

One of the parameters of a binary operator must be the containing type 二进制运算符的参数之一必须是包含类型

how should i implement this? 我应该如何实施呢?

You cannot define an operator for another class. 您不能为另一个类定义运算符。

One alternative would be to create an extension method like so: 一种替代方法是创建一个扩展方法,如下所示:

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

This is because you are trying to create an operator overload inside a class definition which is not of byte . 这是因为您试图在不是byte的类定义内创建运算符重载。

suppose this 假设这个

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

This compiles fine, because I am overloading operator + for Program and my operands on which I am performing + operations are of type Program too. 这样编译就可以了,因为我正在重载Program的operator +,而我正在执行+的操作数也属于Program类型。

I preferred this solution: 我更喜欢这种解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM