如何通过使用运算符重载来获取数组的并集?

时间:2017-03-12 19:31:32

标签: c# arrays

我接受一个类Set一个类,它将一个数组保存在类的构造函数中,我们初始化数组并生成该数组的两个对象,如

我需要在+运算符中两个数组的并集应该来 引导我。在操作员参数a和b,它也给出错误

public class seta
{
public seta(int size)

{
    this.size = Size;
    int[] array = new int[size]



}

private int size;

public int Size
{
    get { return size; }
    set { size = value; }
}


 Console.WriteLine ("enter  size of an array   aray");`
`
            int a = Convert.ToInt32(Console.ReadLine());

            seta obja = new seta(a);

            Console.WriteLine("enter  size of an array   aray");
            int b = Convert.ToInt32(Console.ReadLine());

            seta objb = new seta(b);
        }

            public static double operator + (  a , b )
        {
        }

1 个答案:

答案 0 :(得分:0)

此代码将创建存储在class SetA { }中的两个随机数组,然后找到与operator +的联合。在引擎盖下,它只是调用Enumerable.Union()

public class SetA
{
    static Random rng = new Random();
    int[] data;
    public SetA(int[] data)
    {
        this.data=data;
    }
    public SetA(int size)
    {
        this.data=new int[size];
        for (int i = 0; i<data.Length; i++)
        {
            data[i]=rng.Next(0, 100);
        }
    }
    public int Size { get { return data.Length; } }
    public int[] Data { get { return data; } }
    public static SetA operator +(SetA a, SetA b)
    {
        return new SetA(a.data.Union(b.data).ToArray());
    }
}
class Program
{
    static void Main(string[] args)
    {
        SetA a = new SetA(100);
        SetA b = new SetA(50);

        SetA c = a+b;
        int n = c.Size;
    }
}