我是C#編程的新手,遇到了一個難以逾越的障礙。編譯錯誤CS0305
我得到這個編譯錯誤:
CS0305: Using the generic type 'System.Collections.Generic.IEnumerable' reuires 1 type arguments
與此代碼;
class Program
{
static void Main(string[] args)
{
Car c = new Car();
c.PetName = "Frank";
c.Speed = 55;
c.colour = "Green";
Console.WriteLine("Name = : {0}", c.PetName);
c.DisplayStats();
Garage carLot = new Garage();
// Hand over each car in the collection
foreach (Car c in carLot)
{
Console.WriteLine("{0} is going {1} MPH",
c.PetName, c.CurrentSpeed);
}
Console.ReadLine();
}
class Car
{
//Automatic Properties
public string PetName { get; set; }
public int Speed { get; set; }
public string colour { get; set; }
public void DisplayStats()
{
Console.WriteLine("Car Name: {0}", PetName);
Console.WriteLine("Speed: {0}", Speed);
Console.WriteLine("Color: {0}", colour);
}
}
public class Garage
{
private Car[] CarArray = new Car[4];
// Fill with some car objects on startup.
public Garage()
{
carArray[0] = new Car("Rusty", 30);
carArray[1] = new Car("Clunker", 55);
carArray[2] = new Car("Zippy", 30);
carArray[3] = new Car("Fred", 30);
}
}
public IEnumerator GetEnumerator()
{
foreach (Car c in carArray)
{
yield return c;
}
}
}
我該如何解決這個問題?
什麼地方從代碼丟失:一類必須實現的'IEnumerable'或IEnumerable的''接口在'foreach'語句中使用。我在Garage類中沒有看到。 –
2011-05-01 03:39:42
@Etienne,它更直觀地實現這些接口之一,但它不是必需的。*有一個合適的'GetEnumerator'方法就足夠了。如果感興趣,請參閱C#語言規範的第8.8.4節。 – 2011-05-01 03:52:33
@安東尼有趣,不知道。再次,'Garage'類中沒有'GetEnumerator'方法。 – 2011-05-01 03:56:46