[英]C# - How to use the same object more than once with different values?
关于OOP,我来自Python背景,在Python中,您可以多次使用一个对象,并为该对象分配不同的值。
例如,在Python中,我可以执行以下操作:
class Car:
def __init__(self, make, model, colour):
self.make = make
self.model = model
self.colour = colour
carList = []
car = Car("Ford", "Mondeo", "Red")
carList.append(car)
car = Car("Ford", "Focus", "Silver")
carList.append(car)
print(carList[0].make + " " + carList[0].model)
print(carList[1].make + " " + carList[1].model)
输出为:
Ford Mondeo
Ford Focus
在C#中,情况会有所不同,如果有人愿意向我说明为什么会这样,我将不胜感激。
码:
using System;
using System.Collections.Generic;
namespace Test
{
class Car
{
private string make, model, colour;
public Car()
{
}
public void carDesc(string mke, string mdl, string clr)
{
make = mke;
model = mdl;
colour = clr;
}
public string getMake()
{
return make;
}
public string getModel()
{
return model;
}
public string getColour()
{
return colour;
}
}
class Test
{
static void Main(string[] args)
{
List<Car> carList = new List<Car>();
Car car = new Car();
car.carDesc("Ford", "Mondeo", "Red");
carList.Add(car);
car.carDesc("Ford", "Focus", "Silver");
carList.Add(car);
Console.WriteLine(carList[0].getMake() + " " + carList[0].getModel());
Console.WriteLine(carList[1].getMake() + " " + carList[1].getModel());
Console.ReadKey();
}
}
}
输出:
Ford Focus
Ford Focus
另外,如果不可能在这里做我想做的事情,那么我将如何着手解决这个问题以实现相同的目标? 之所以这样做,是因为我希望能够动态(?)创建一个对象,而不是硬编码最终用户要填充的一定数量的对象。
提前致谢。
这在Python中创建了两个不同的 Car
对象,除了类型不同之外,它们彼此无关:
Car("Ford", "Mondeo", "Red")
Car("Ford", "Focus", "Silver")
因此,在C#中,您还应该创建两个不同的 Car
对象:
new Car("Ford", "Mondeo", "Red");
new Car("Ford", "Focus", "Silver");
因此,您的Car
构造函数应该看起来像这样:
public Car(string mke, string mdl, string clr)
{
make = mke;
model = mdl;
colour = clr;
}
您应该创建Car
类的两个不同实例:
List<Car> carList = new List<Car>();
Car car = new Car();
car.carDesc("Ford", "Mondeo", "Red");
carList.Add(car);
// You should add this: creating another instance of Car class
car = new Car();
car.carDesc("Ford", "Focus", "Silver");
carList.Add(car);
Console.WriteLine(carList[0].getMake() + " " + carList[0].getModel());
Console.WriteLine(carList[1].getMake() + " " + carList[1].getModel());
Console.ReadKey();
这与您正在做的事情不同。 如果查看Python语句,您将创建2个新对象。 。
car = Car("Ford", "Mondeo", "Red")
carList.append(car)
car = Car("Ford", "Focus", "Silver")
C#中的等效项是
car = new Car("Ford", "Mondeo", "Red");
carList.Add(car);
car = new Car("Ford", "Focus", "Silver");
carList.Add(car);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.