我是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