C#一起加入2个或更多课程?

时间:2012-01-22 19:04:48

标签: c#

所以这可能听起来像是一个n00b问题,但我想把2个类合并在一起。

像这样:

Ball oneBall = new Ball("red", 20);
Ball anotherBall = new Ball("blue",40);


Ball BigBall = new Ball(oneBall + anotherBall);

BigBall.size() //should say 60 right? 

我知道你会有类似的东西

class Ball{


  public Ball(string Name , int size){}

// But to merge to of them? 

  public Ball(Ball firstBall, Ball secondBall){} //I know the arguments have to be added
{}


} 

所以我的问题是什么是重载(对吗?)假设看起来像?

谢谢,

5 个答案:

答案 0 :(得分:6)

是的,您可以定义构造函数重载。

public class Ball
{
    public string Name { get; private set; }
    public int Size { get; private set; }

    public Ball(string name, int size) 
    { 
        this.Name = name;
        this.Size = size;
    }

    // This is called constructor chaining
    public Ball(Ball first, Ball second)
        : this(first.Name + "," + second.Name, first.Size + second.Size)
    { }
} 

合并两个球:

Ball bigBall = new Ball(oneBall, anotherBall);

请注意,您正在调用构造函数重载,而不是+运算符。

答案 1 :(得分:5)

public class Ball
{
    public int Size { get; private set; }
    public string Name { get; private set; }

    public Ball(string name , int size)
    {
        Name = name;
        Size = size;
    }

    public Ball(Ball firstBall, Ball secondBall)
    {
        Name = firstBall.Name + ", " + secondBall.Name;
        Size = firstBall.Size + secondBall.Size;
    }
} 

答案 2 :(得分:5)

您希望重载Ball的加法运算符,例如:

public static Ball operator +(Ball left, Ball right)
{
    return new Ball(left.Name + right.Name, left.Size + right.Size);
}

虽然使Ball构造函数接收2 Ball并添加它们可能更具可读性,但如果你真的想写new Ball(ball1 + ball2)那么运算符重载就可以了。如果您使用构造函数执行此操作,那么您的代码将如下所示:new Ball(ball1, ball2)

答案 3 :(得分:2)

这是正确的,只需将两个球作为两个参数传递给第二个过载

Ball BigBall = new Ball(oneBall , anotherBall);

并调整过载,以便将两个球尺寸加在一起:

public Ball(Ball firstBall, Ball secondBall){} //I know the arguments have to be added
{
    this.size = firstBall.size + secondBall.size;
}

答案 4 :(得分:2)

如果有意义,您可以为您的类型定义加法运算符:

public static operator+(Ball rhs, Ball lhs) 
{
    return new Ball(lhs.Size + rhs.Size);
}

只有在语义上将Ball的两个实例一起添加时才这样做。