如何解决C#如何创建抽象类添加对象到数组?
1在这段代码的末尾,我要接收所有输入值并将它们添加到中以添加到Car对象。
但是当我尝试实现抽象类时出现错误,有人知道解决此问题的方法吗?即如何将抽象类的对象添加到列表/数组。提前非常感谢
string[] values = input.Split(',');
string make = values[0];
string model = values[1];
if (double.TryParse(values[2],out double fuelAmount) == false)
Console.WriteLine("Failed to parse the fuelAmount from the file");
if (double.TryParse(values[3],out double mileage) == false)
Console.WriteLine("Failed to parse the mileage from the file");
// create a new car
myCarList.Add(new Car(make,model,fuelAmount,mileage));
解决方法
您可以创建一个实现抽象类的类,然后使用该类将其添加到List 或数组中,因为您无法创建抽象类的实例。
public abstract class your_class_name_1
{
//do your stuff here
}
//inherit your abstract class so you can access the members of your abstract class
public class your_class_name_2 : your_class_name_1
{
//do your stuff here
}
//and in your main method
static void Main(string[] args)
{
your_class_name_2 myclass = new your_class_name_2();
//then do your code here
}
我不知道哪个班是哪个班,但无论如何希望这对您有帮助
,该错误与将对象添加到列表无关。它是关于创建抽象类的对象。这违反了抽象类的定义。在OOP中,不允许实例化抽象类。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。