对于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
另外,如果我不想在这里做我想做的事情,我将如何解决这个问题以达到同样的目标?我想这样做的原因是因为我希望能够动态地(?)创建一个对象而不是硬编码最终用户要填充的一定数量的对象。
提前致谢。
答案 0 :(得分:4)
这在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;
}
答案 1 :(得分:2)
您应该创建 两个 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();
答案 2 :(得分:1)
这与你正在做的事情不一样。如果你看一下你的Python语句,你就会创建两个新对象。
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);