我有两个班级,Plant(基础)和IndoorPlant(继承人)。整个问题是,当我想通过将方法绑定到按钮来访问后代类的方法时,会出现错误:
无法转换
void为object.
int五"название программы".IndoorPlant。
下面我提供了类的代码以及我将方法绑定到的按钮:
internal class Plant
{
public string name;
public string classPlant;
public double height;
public Plant()
{
name = "Растение";
height = 0;
classPlant = "неизвестно";
}
public Plant(string name, string classPlant, double height)
{
this.name = name;
this.height = height;
this.classPlant = classPlant;
}
public Plant(Plant p)
{
name = p.name;
height = p.height;
classPlant = p.classPlant;
}
public virtual void Print()
{
Console.WriteLine($"Название растения - {name}, Класс - {classPlant}, Высота = {height}");
}
}
internal class IndoorPlant : Plant
{
public string view;
public int count;
public IndoorPlant() : base()
{
view = "";
count = 0;
}
public IndoorPlant(string name, string classPlant, double height, string view, int count) : base(name, classPlant, height)
{
this.view = view;
this.count = count;
}
public IndoorPlant(IndoorPlant t) : base(t.name, t.classPlant, t.height)
{
this.view = t.view;
count++;
}
public IndoorPlant(Plant p, string view, int count)
{
this.view = view;
this.count = count;
}
public override void Print()
{
base.Print();
Console.WriteLine($"Вид - {view}\nКол-во - {count}");
}
}
private void button1_Click(object sender, EventArgs e)
{
Plant P1 = new Plant();
IndoorPlant IP1 = new IndoorPlant();
listBox1.Items.Add("Комнатное растение. Конструктор без параметров");
listBox1.Items.Add(IP1.Print()); //<-- не удается преобразовать из "void" в "object".
IndoorPlant IP2 = new IndoorPlant(4);//<-- не удается преобразовать из "int" в "название программы".IndoorPlant.
listBox1.Items.Add("Комнатное растение. Конструктор с параметром");
listBox1.Items.Add(IP2.Print());
IndoorPlant IP3 = new IndoorPlant(IP2);//<-- не удается преобразовать из "void" в "object".
listBox1.Items.Add("Комнатное растение. Конструктор копирования");
listBox1.Items.Add(IP3.Print());//<-- не удается преобразовать из "void" в "object".
}
我用注释突出显示了编译器抱怨的地方。
据我了解,您不需要在控制台中输出,并且您希望在表单上显示调用的结果(更准确地说,在您的列表中
listBox1)。Print将类中的方法更改为:以及:
您的线路:
在:
好吧,现在稍微解释一下:
Print您正在尝试将方法调用的结果添加到列表中void。但是,可惜,你没有这样的构造函数。