简体   繁体   中英

Change class property value based on passed parameter

I have the class Car as shown. Car has values assigned to the properties. How can i change these values depending on a passed parameter when making a new instance of the class? (eg BMW, Volvo etc) In the constructor?

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

For example if i created the class: Car car = new Car("BMW");

You could use a switch block in your constructor and assign the values to your properties. If an invalid argument is passed to your constructor, you could throw an exception:

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

I suppose you just need a constructor accepting a single parameter:

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

yes, you should create a constructor Car with parameters, in your example you should take a string parameter

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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