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

查看:73
本文介绍了“二进制运算符的参数之一必须是包含类型".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我在写这篇文章时会不断收到我不知道如何解决的错误.任何帮助将不胜感激!

For some reason when I write this I keep getting an error that I don''t know how to solve. Any help would be very much appreciated!

public static byte[] operator +(byte[] l, byte[] r)
{
    List<byte> blist = l.ToList();
    blist.AddRange(r);
    return blist.ToArray();
}

推荐答案

请参阅此 C#运算符重载 [ ^ ]并查看它是否也不能回答您的问题.
See this C# Operator Overloading[^] and see if it does not answer your question also.


您不能真正重载数组"类的运算符,因为您只能重载类本身内部的运算符,而不能重载对于内置类型,如byte [].查看此讨论:
http://stackoverflow.com/questions/1687395/overloading-the-operator- to-add-two-arrays [ ^ ]

目前甚至不可能通过此处讨论的扩展方法来做到这一点:
http://stackoverflow.com/questions/5518468/is-it-可能的-定义-扩展操作员方法 [ ^ ]

因此,最好的解决方案是编写一个标准函数,而不会像这样重载运算符:
You can''t really overload an operator for the "array" class, since you can only overload operators inside the class itself and not for inbuilt types as byte[]. See this discussion:
http://stackoverflow.com/questions/1687395/overloading-the-operator-to-add-two-arrays[^]

It is currently even not possible to do this in an extension method as discussed here:
http://stackoverflow.com/questions/5518468/is-it-possible-define-an-extension-operator-method[^]

So, your best possible solution is to write a standard function without operator overloading like:
public static byte[] Add(byte[] l, byte[] r)
{
  List<byte> blist = l.ToList();
  blist.AddRange(r);
  return blist.ToArray();
}


您好,
报价:

如果要在AA和BB类型之间重载le +运算符,则必须在AA或BB类中而不是在A名为Program的类(就像您一样).

不幸的是,您无法在Array类中编写代码.

您可以做的是

创建自己的实现IList的类
并将+运算符放在该类上.

When you want to overload le + operator between type AA and BB, you must do it in the class AA or BB and not in a class named Program (like you did).

Unfortunatly, you cannot write code in the Array class.

What you can do is to

create your own class that implements IList
and put the + operator on that class.

我在网上发现了这一点,这是真的.我知道您为了方便起见基本上要重载运算符,但是您不能这样做,因此必须编写一个辅助方法.因此,如果您使用的是.Net 3.5或更高版本,这是我为您提供的解决方案.

I found this on the net and it''s true. I know you want to basically overload the operator for convenience, but you cannot do that, so you have to write a helper method. So if you are using .Net 3.5 or higher, here is my solution to you.

public static byte[] Append(byte[] baseData, byte[] newData)
{
  return baseData.Concat(newData).ToArray();
}


如果您使用的是较旧的.Net框架,


If you are using an older .Net framework,

public static byte[] Append(byte[] baseData, byte[] newData)
{
  byte[] result = new byte[baseData.Length + newData.Length];
  baseData.CopyTo(result, 0);
  newData.CopyTo(result, baseData.Length);

  return result;
}


希望对您有所帮助


Hope this helps, regards


这篇关于“二进制运算符的参数之一必须是包含类型".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆