【发布时间】:2015-10-20 04:17:07
【问题描述】:
我是 OOP 的新手,所以如果可能的话,我不知道我在问什么,但这里是。我的表单上有两个单选按钮“radiobutton1”和“radiobutton2”。我有一个带有名为“car1”的实例的车辆类。我还有一个 Motor 类,它有两个实例,分别称为“smallMotor”和“largeMotor”。我正在尝试创建一个名为“SetMotor”的方法,该方法应该将 smallMotor 或 largeMotor 设置为 car1 的电机。此方法应该采用两个布尔值,由两个单选按钮表示,以确定为 car1 设置哪个电机对象。我尝试了以下方法,但它不起作用并给了我错误。这是我的代码:
主要形式:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
Motor largeMotor;
Motor smallMotor;
Vehicle car1;
public Form1()
{
InitializeComponent();
largeMotor = new Motor(2000);
smallMotor = new Motor(1000);
car1 = new Vehicle();
}
private void button1_Click(object sender, EventArgs e)
{
car1.SetModel(textBoxModel.Text);
car1.SetNumDoors((int)numericUpDown1.Value);
car1.SetMotor(radioButton1.Checked, radioButton2.Checked);
}
}
}
我的汽车班:
class Motor
{
private int power;
public Motor(int p)
{
power = p;
}
}
车辆类:
class Vehicle
{
private Motor motor;
public void SetMotor(bool smallMotor, bool largeMotor)
{
if (largeMotor)
{
motor = largeMotor;
}
else
motor = smallMotor;
}
}
这给我的错误是:
错误 6 无法将类型“bool”隐式转换为“WindowsFormsApplication12.Motor”。
那么,是否可以将两个电机对象绑定到单选按钮?非常感谢任何帮助。
【问题讨论】:
-
你的
motor对象是什么?,一定有motor.IsLarge之类的 -
largeMotor是布尔值,而motor是电机类的对象,这就是为什么你会得到Cannot implicitly convert type 'bool' to 'WindowsFormsApplication12.Motor'。 -
你应该知道你的源代码中多了一个括号
-
您能否添加更多源代码,因为我目前看到的主要错误是您的电机字段(猜测它是您表单中的字段)并且您说我的电机实例等于没有意义的布尔值。 @ShaminderSAujla 说的非常好。您可以重构您的 Vehicule 类以拥有一个名为 IsLarge 的属性。并且不需要两个单选按钮。一个单选按钮就可以了。未选中时,IsLarge 为假(小电机),选中时,isLarge 为真(大电机)。瞧,不需要 2 个单选按钮