我是 OOP 的新手,所以我不知道我问的问题是否可能,但我已经开始了。我的表单上有两个单选按钮“radiobutton1”和“radiobutton2”。我有一个 Vehicle 类,其中包含一个名为“car1”的实例。我还有一个 Motor 类,其中包含两个名为“smallMotor”和“largeMotor”的实例。我正在尝试创建一个名为“SetMotor”的方法,该方法应该将 smallMotor 或 largeMotor 设置为 car1 的电机。此方法应该采用两个 bool 值,由两个单选按钮表示,以确定为 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;
}
}
这给我的错误是:
Error 6 Cannot implicitly convert type 'bool' to 'WindowsFormsApplication12.Motor'.
那么,是否可以将两个电机对象绑定(bind)到单选按钮上呢?非常感谢任何帮助。
最佳答案
在您当前的代码中,您正试图将 bool
值分配给 Motor
,由于您的代码是强类型的,因此无法完成。
largeMotor
和 smallMotor
对象之间没有区别。如果您以后需要知道电机是大还是小,您的 Vehicle
对象将无法告诉您。就您的类(class)结构而言,这是一个快速建议:
class Vehicle
{
public Motor Motor
{
get;
set;
}
}
class Motor
{
public MotorType Type
{
get;
set;
}
}
enum MotorType
{
Large,
Small
}
class SomeClass
{
public void SetMotorType(bool isSmall)
{
// This object would probably come from some place else
Vehicle vehicle = new Vehicle();
vehicle.Motor = new Motor { Type = (isSmall) ? MotorType.Small : MotorType.Large };
}
}
现在,Vehicle.Motor.MotorType
将让您随时了解电机是大还是小。
编辑:
暂时忘掉编程和 OOP,想想现实世界。有一辆汽车,它有发动机和轮胎。在编程中,类是一个完整的真实世界对象的表示(仅适用于现在)。现在,按照这种理解,您的代码中应该有一个 Car
类。现在,汽车有发动机和轮胎。发动机和轮胎本身也很完整。所以您需要一个用于Engine
和Tyre
的类。接下来,你知道汽车有发动机和轮胎。要在代码中关联这三个类,您可以使用如下属性:
class Car
{
public Engine Engine{get;set;}
// Since car has more than one tyres, it should be one to many relation
public List<Tyre> Tyres{get;set;}
}
现在,引擎可以被分解成活塞、汽缸等部分。根据您想要的粒度,活塞可以是引擎的一个属性,也可以是一个类,具有 MadeOf、Diameter、Length 等属性等。为了简单起见,我不会做更深入的。那么,您将如何将这些属性链接到引擎?通过使用属性。因此,
class Engine{
// Or any other Piston attribute you are interested in.
public int PistonId{get;set;}
public decimal CylinderVolume{get;set;}
}
类似地,Tires to 将使用它们所具有的属性来定义。像半径一样,它们是否是无内胎和其他属性。所以,
class Tyre{
public int radius{get;set;}
public bool IsTubeless{get;set;}
}
现在,您可以说 Car 有无内胎轮胎,所以我们可以将 IsTubeless
属性放入汽车中。但是从逻辑上考虑,Tyre
类对象知道它是否是无内胎更有意义。这就是您定义类的方式。
之前,我提到类代表完整的现实世界对象。一旦你深入挖掘并偶然发现抽象类,你就会意识到这不是真的。但留到以后再说。
关于c# - 将对象绑定(bind)到单选按钮 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227907/