根据传递的参数更改类属性值

时间:2021-02-02 14:46:34

标签: c#

我有如图所示的 Car 类。 Car 具有分配给属性的值。在创建类的新实例时,如何根据传递的参数更改这些值? (例如宝马、沃尔沃等)在构造函数中?

public class Car {
  public string Engine { get; set; } = "Engine1"; 
  public string Body { get; set; } = "Body1";
  public string Wheels { get; set; } = "Wheels1";
}

例如,如果我创建了类:Car car = new Car("BMW");

3 个答案:

答案 0 :(得分:1)

您可以在构造函数中使用 switch 块并将值分配给您的属性。如果传递给构造函数的参数无效,则可能引发异常:

public class Car {
  public string Engine { get; set; }
  public string Body { get; set; }
  public string Wheels { get; set; }

  public Car(string type)
  {
    switch(type)
    {
      case "BMW":
        Engine = "Engine1";
        Body = "Body1";
        Wheels = "Wheels1";
        break;
      case "Volvo":
        Engine = "Engine2";
        Body = "Body2";
        Wheels = "Wheels2";
        break;
      default:
        throw new ArgumentException("invalid type!");
    }
  }
}

答案 1 :(得分:1)

我想你只需要一个接受单个参数的构造函数:

public class Car 
{
    public string Engine { get; set; } = "Engine1"; 
    public string Body { get; set; } = "Body1";
    public string Wheels { get; set; } = "Wheels1";
    public Car(string type)
    {
        switch (type)
        {
            case "BMW": 
                Engine = "BMW Engine";
                Body = "BMW Body";
                Wheels = "BMW Wheels";
                break;
            case "VW": ...
            case default: throw new ArgumentException("Not implemented");
    }
}

答案 2 :(得分:0)

是的,你应该创建一个构造函数 带参数的汽车,在您的示例中,您应该采用字符串参数

Car(string Engine, string Body . . . )
{
//here in the constructor body, you should assign the value you took as 
//a parameter to you class internal field
//for example 
this.Engine = Engine;
}