gpt4 book ai didi

c# - 如何为表单应用程序中的所有实例仅调用一次 Method DriveMe() 或 color() 以减少重复。 C#

转载 作者:行者123 更新时间:2023-11-30 23:33:40 25 4
gpt4 key购买 nike

表单有 4 个单选按钮和 2 个按钮。我可以选择 VehicleType 并单击按钮(代表方法)以显示所选车辆的属性。我想为所有 if else 条件调用 DriveMe() 和 color() 方法,但只调用一次。有什么方法可以替换 IF ELSE 来实现这一点。

namespace vehicles
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{

}
public class vehicle
{
public string _VehicleType;
public string VehicleType { get; set; }
public string Vehiclecolor { get; set; }
public virtual void DriveMe()
{
MessageBox.Show(VehicleType);
}
public virtual void color()
{
MessageBox.Show(Vehiclecolor);
}
}
public class car : vehicle
{

}
public class truck: vehicle
{

}
public class bike : vehicle
{

}
public class train : vehicle
{

}

private void button1_Click_1(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
car v = new car();
v.VehicleType = "Nissan Murano 2007";
v.DriveMe();
}
else if (radioButton2.Checked == true)
{
truck v = new truck();
v.VehicleType = "Dodge Truck";
v.DriveMe();
}
else if (radioButton3.Checked == true)
{
bike v = new bike();
v.VehicleType = "Hardley Davidson Bike";
v.DriveMe();
}
else if (radioButton4.Checked == true)
{
train v = new train();
v.VehicleType = "Train";
v.DriveMe();
}
else
{
vehicle v = new vehicle();
v.VehicleType = "Please Select the Vehicle Type";
v.DriveMe();
}
}

private void button2_Click(object sender, EventArgs e)
{
if (radioButton1.Checked == true)
{
car v = new car();
v.Vehiclecolor = "Black";
v.color();
}
else if (radioButton2.Checked == true)
{
truck v = new truck();
v.Vehiclecolor = "White";
v.color();
}
else if (radioButton3.Checked == true)
{
bike v = new bike();
v.Vehiclecolor = "Red";
v.color();
}
else if (radioButton4.Checked == true)
{
train v = new train();
v.Vehiclecolor = "Blue";
v.color();
}
else
{
vehicle v = new vehicle();
v.Vehiclecolor = "Please Select the Vehicle Type";
v.color();
}

}

}

}

最佳答案

由于您的所有类都继承自 vehicle,因此您可以稍微简化您的代码。 DriveMe()color() 是在基类上定义的,因此它可用于所有更多的派生类。

private void button2_Click(object sender, EventArgs e)
{
vehicle v = null;

if (radioButton1.Checked == true)
{
v = new car();
v.Vehiclecolor = "Black";
}
else if (radioButton2.Checked == true)
{
v = new truck();
v.Vehiclecolor = "White";
}
else if (radioButton3.Checked == true)
{
v = new bike();
v.Vehiclecolor = "Red";
}
else if (radioButton4.Checked == true)
{
v = new train();
v.Vehiclecolor = "Blue";
}
else
{
v = new vehicle();
v.Vehiclecolor = "Please Select the Vehicle Type";
}

v.color();
}

您的其他函数可以用类似的方式重写。

关于c# - 如何为表单应用程序中的所有实例仅调用一次 Method DriveMe() 或 color() 以减少重复。 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33836835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com