在c#中,根据用户输入从许多类中只创建一个类对象
本文关键字:创建 一个 对象 许多类 用户 输入 | 更新日期: 2023-09-27 18:12:58
我正在编写一个程序,其中我有5个品牌,每个品牌一个类。我只想创建用户想知道的那个类的实例。除了用户输入的品牌之外,不应该创建其他对象。我使用switch语句,但这不起作用。有更好的方法吗?如何做到这一点,使该特定对象在整个主要范围内保持不变。这是我的代码。
string brandInput= brand.brandNameEvaluator();
// above is method which is getting input of brand name from user.
switch (brandInput)
{
case "Suzuki":
Suzuki suzuki = new Suzuki();
break;
case "Honda":
Honda honda = new Honda();
break;
case "Ferrari":
Ferrari ferrari = new Ferrari();
break;
case "Toyota":
Toyota toyota = new Toyota();
break;
case "BMW":
BMW bmw = new BMW();
break;
default:
Console.WriteLine("Something went wrong.. We are sorry for the inconvenience");
break;
}
为car创建一个基类,并从它继承不同的类型
public abstract class Car
{
//Properties
}
public class Suzuki : Car {}
然后在你的代码中:
Car car = null;
string brandInput= brand.brandNameEvaluator();
switch (brandInput)
{
case "Suzuki":
car = new Suzuki();
break;
case "Honda":
car = new Honda();
break;
case "Ferrari":
car = new Ferrari();
break;
case "Toyota":
car = new Toyota();
break;
case "BMW":
car = new BMW();
break;
}
if (car == null)
{
//Do something and exit
}
另外,我建议使用Factory设计模式来创建汽车。
这5个类应该继承自一个抽象基类,它允许您创建该数据类型。转换方法仍然有效。例子:
BaseCar car;
string brandInput= brand.brandNameEvaluator();
switch (brandInput)
{
case "Suzuki":
car = new Suzuki();
break;
case "Honda":
car = new Honda();
break;
case "Ferrari":
car = new Ferrari();
break;
case "Toyota":
car = new Toyota();
break;
case "BMW":
car = new BMW();
break;
default:
Console.WriteLine("Something went wrong.. We are sorry for the inconvenience");
break;
}