繁体   English   中英

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

[英]Change class property value based on passed parameter

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

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

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

您可以在构造函数中使用 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!");
    }
  }
}

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM