Playing with cubes II

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);
  }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值