需要帮助重载C#

时间:2018-12-02 21:07:41

标签: c# parameter-passing

我是C#的新手,我正在尝试将yourCar重载到Car类中,在该类中将其实例化,然后在以后再次显示在主类中。 我一直遇到的问题是要确保我超载,因为默认值保持不变,而不是新价格和默认颜色。

// Creates a Car class
// You can construct a Car using a price and color
// or just a price, in which case a Car is black
// or no parameters, in which case a Car is $10,000 and black
using static System.Console;
class DebugNine3
{
   static void Main()
   {
      Car myCar = new Car(32000, "red");
      Car yourCar = new Car(14000);
      Car theirCar = new Car();
      WriteLine("My {0} car cost {1}", myCar.Color,
         myCar.Price.ToString("c2"));
      WriteLine("Your {0} car cost {1}",
         yourCar.Color, yourCar.Price.ToString("c2"));
      WriteLine("Their {0} car cost {1}",
         theirCar.Color, theirCar.Price.ToString("c2"));
  }
}

class Car
{
  // private string color;
  // private int price;
  // 
  public string color;
  public int price;

   //DEfault no values entered
   public Car() : this(10000, "black")
   {

   //One value entered
   public Car(int price) : this()
   {
   }

   //both values entered
   public Car(int price, string color)
   {

       Price = price;
       Color = color;
   }

   //what it does with the values passed to it 
   public string Color
   {
      get
      {
         return color;
      }
      set
      {
         color = value;
      }
   }

   public int Price
   {
      get
      {
         return price;
      }
      set
      {
         price = value;
      }
   }
}

我得到的结果是: 我的红色汽车价值$ 32,000.00 您的黑车价格为$ 10,000.00 他们的黑车要花一万美元

1 个答案:

答案 0 :(得分:2)

您没有设置任何内容。您的public Car(int price)构造函数不执行价格更改,而是执行以下操作:

public Car(int price) : this()
{
    this.Price = price;
}

这样,将触发默认构造函数(并设置默认价格和颜色),然后设置正确的新颜色。

修改 此外,设置默认参数的更好方法是通过参数本身而不是使用默认值来调用它。参见示例:

class Test {
  public int A {get; set;} = 5;
  public string B {get; set;} = "test";

  public Test() {
  }

  public Test(int a) {
    this.A = a;
  }

  public Test(int a, string b) {
    this.A = a;
    this.B = b;
  }
}