您的位置:首页 > 其它

Playing with cubes II

2015-09-27 21:15 176 查看

Description:

Hey Codewarrior!

You already implemented a Cube class, but now we need your help again! I'm talking about constructors. We don't have one. Let's code two: One taking an integer and one handling no given arguments!

Also we got a problem with negative values. Correct the code so negative values will be switched to positive ones!

The constructor taking no arguments should assign 0 to Cube's Side property.

http://www.codewars.com/kata/playing-with-cubes-ii/csharp

using System;

public class Cube
{
private int Side;

//This cube needs your help.
//Define a constructor which takes one integer and assignes its value to 'Side'
public Cube()
{}

public Cube(int side)
{
this.Side = Math.Abs(side);
}

public int GetSide()
{
return this.Side;
}

public void SetSide(int s)
{
this.Side = Math.Abs(s);
}
}


可以使用this来处理构造函数,无参构造函数,字段的默认值,可以通过调用有参函数来处理

赋值的时候,可以调用类本身的函数

public class Cube
{
private int Side;

//This cube needs your help.
//Define a constructor which takes one integer and assignes its value to 'Side'
public Cube(int s)
{
SetSide(s);
}

public Cube()
: this(0)
{

}
public int GetSide()
{
return Side;
}

public void SetSide(int s)
{
Side = System.Math.Abs(s);
}
}


可以使用函数的缺省参数

using System;

public class Cube
{
private Int32 _side;

public Cube(Int32 Side = 0){
SetSide(Side);
}

public Int32 GetSide()
{
return this._side;
}

public void SetSide(Int32 Side)
{
this._side = Math.Abs(Side);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: