2014-01-28 168 views
0

例如,我們有下一個類:如何使用變量作爲名稱從類創建對象?

class Car 
{ 
    public string Make { get; set; } 
    public string Model {get;set;} 
    public int Year {get;set;} 
    public string Color {get;set;} 
} 

並與幾個車模一個數組:

string[] cars = { "Honda", "BMW", "Audi"}; 

我想創建一個數組中的每個項的對象。如果你的foreach內創建Car例如我的下一個代碼,但沒有成功

foreach (var item in cars) 
{ 
    Car item = new Car(); 
} 
+0

您可以初始化您的對象的集合,並在每次循環中添加它 – aw04

回答

2

在環不能使用相同的變量item。另外,實例並沒有真正使用,因爲一旦循環結束它們就會消失。然而

您可能需要使用LINQ (a library used to manipulation collections)及以上Car對象的集合字符串名稱映射,

var makes = { "Honda", "BMW", "Audi" }; 
var cars = makes.Select(make => new Car(make)); 

對於這個工作,你需要一個構造函數添加到您的類,它需要一個製造商的名字,

public class Car 
{ 
    public Car(string make) 
    { 
     this.Make = make; 
    } 

    public string Make { get; set; } 
    public string Model {get; set; } 
    public int Year { get; set; } 
    public string Color { get; set; } 
} 

或者,你可以使用類屬性初始化設置作出財產,

var makes = { "Honda", "BMW", "Audi" }; 
var cars = makes.Select(make => new Car { Make = make }); 
1

試過了,你不能訪問的foreach範圍之外的這些實例。首先創建一個Car List

var carList = new List<Car>(); 

然後用一個for循環:

for(int i=0; i<cars.Length; i++) 
{ 
    Car item = new Car(); 
    item.Make = cars[i]; 
    // set other properties 
    carList.Add(item); 
} 
0

如何:

class Car 
{ 
    public string Make { get; set; } 
    public string Model {get;set;} 
    public int Year {get;set;} 
    public string Color {get;set;} 

    public Car(string make) 
    { 
     Make = make; 
    } 
} 

而現在你的循環:

List<Car> cars = new List<Car>(); 
foreach (var item in cars) 
{ 
    Car car = new Car(item); 
    cars.Add(car); 
} 
0

您可以在一行一點點額外的代碼

Car[] cars = new [] { new Car {Make = "Honda"}, 
         new Car {Make = "BMW"}, 
         new Car {Make = "Audi"} 
         }; 

或一個LINQ投影做到這一點:

string[] cars = { "Honda", "BMW", "Audi"}; 
Car[] cars = cars.Select(s => new Car {Make = s}) 
       .ToArray(); 
+0

此代碼是錯誤的。你正在轉換成Car []而不是字符串[]。 – Dismissile

0

爲您的類添加一個接受「make」參數的構造函數。將其設置爲您實例上的Make成員。

class Car 
{ 
    public string Make { get; set; } 
    public string Model {get;set;} 
    public int Year {get;set;} 
    public string Color {get;set;} 

    public Car(string make) 
    { 
     this.Make = make; 
    } 
} 
0

您可以構建每輛車就像這樣:

foreach (var item in cars) 
{ 
    // Note that you can't reuse 'item' here 
    Car newCar = new Car { Make = item }; 
} 

你會希望把每newCar在列表中,或內循環用它做什麼。

你也可以使用LINQ來做到這一點的一條線:

var carList = cars.Select(x => new Car { Make = x }); 
0

這應該工作:

foreach (string name in cars) 
{ 
    Car item = new Car() { Make = name }; 
} 
1

您需要設置上車的一些信息,並在某處存儲所有的實例。

 string[] carMakes = { "Honda", "BMW", "Audi" }; 
     List<Car> cars = new List<Car>(); 

     foreach (var carMake in carMakes) 
     { 
      cars.Add(new Car(){Make = carMake}); 
     } 
相關問題