class car
{
public double cylinders
{
get;
set;
}
public double topspeed
{
get;
set;
}
public double horsepower
{
get;
set;
}
}
在Window1.cs
{C} 在Window2.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
foreach (car item in carlist) // I cannot use this list because it is in another window.
// I would either like to create a newcarlist in window2 and copy all the contents of the carlist in window1 or need a way to access the carlist in window1.
{
MessageBox.Show(string.Format("Topspeed: {0}, Horsepower: {1} and so on", item.cylinders, item.topspeed, item.horsepower, )); // display topspeed, horsepower, cylinders of each car.
}
}
}
publicpartialclass window2 : Window
{
private IList<car> carlist;
...
public window2(IList<car> carlist)
{
this.carlist = carlist; // this is the reference to the current instance so
// this.carlist refers to the field carlist not the parameter.
InitializeComponent();
}
...
}
using System.Collections.Generic;
namespace Cars
{
publicclass Car
{
publicdouble Cylinders{get; set;}
publicdouble Topspeed{get; set;}
publicdouble Horsepower{get; set;}
}
// we're using inheritance here to make a List<Car>
publicclass CarList: List<Car>
{
privatestaticint defaultCylinders = 8;
privatestaticdouble defaultTopSpeed = 100.0;
privatestaticdouble defaultHorsePower = 90.0;
// we are overloading the Add operator here
// to allow us to check for the need to set
// default values, if they are missing ...
internalvoid Add(Car newCar)
{
if (newCar.Cylinders == 0.0) newCar.Cylinders = defaultCylinders;
if (newCar.Horsepower == 0.0) newCar.Horsepower = defaultHorsePower;
if (newCar.Topspeed == 0.0) newCar.Topspeed = defaultTopSpeed;
// here we call the underlying List<Car> 'Add method
base.Add(newCar);
}
}
}