【发布时间】:2010-12-13 19:55:22
【问题描述】:
这段 C# 代码有什么问题?我试图重载 + 运算符来添加两个数组,但收到如下错误消息:
二元运算符的参数之一必须是包含类型。
class Program
{
public static void Main(string[] args)
{
const int n = 5;
int[] a = new int[n] { 1, 2, 3, 4, 5 };
int[] b = new int[n] { 5, 4, 3, 2, 1 };
int[] c = new int[n];
// c = Add(a, b);
c = a + b;
for (int i = 0; i < c.Length; i++)
{
Console.Write("{0} ", c[i]);
}
Console.WriteLine();
}
public static int[] operator+(int[] x, int[] y)
// public static int[] Add(int[] x, int[] y)
{
int[] z = new int[x.Length];
for (int i = 0; i < x.Length; i++)
{
z[i] = x[i] + y[i];
}
return (z);
}
}
【问题讨论】:
-
关于重载的 MSDN 教程页面有更多信息 - msdn.microsoft.com/en-us/library/aa288467%28VS.71%29.aspx
-
这可能是你的答案:stackoverflow.com/questions/172658/…
-
我们正在考虑将“扩展运算符”添加到假设的 C# 未来版本中,这将解决您的问题。民意调查:你们中的任何人都有这个功能的很棒的场景吗?我们可以获得的真实场景越多,某天就越有可能实现某个功能。按我的方式送他们;您可以使用我博客上的电子邮件链接。
-
谢谢埃里克。这是否意味着我们还将获得“扩展一切”:)
-
我们如何做到这一点,或者我应该放弃多态性直到我成为多神论者?