加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 编译错误CS0305

发布时间:2020-12-16 01:43:37 所属栏目:百科 来源:网络整理
导读:我是C#编程的新手,遇到了一些我无法过去的障碍. 我收到这个编译错误: CS0305: Using the generic type ‘System.Collections.Generic.IEnumerable’ reuires 1 type arguments 用这个代码; class Program { static void Main(string[] args) { Car c = new
我是C#编程的新手,遇到了一些我无法过去的障碍.

我收到这个编译错误:

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有两种变体,泛型变量(在System.Collections.Generic命名空间中)接受一个类型参数,该参数指定了枚举所包含的对象类型.另一个(包含在System.Collections命名空间中)没有类型参数,因此公开了类型对象 – 您似乎声明/使用非泛型变体,但是没有使用System.Collections命名空间.

我认为修复特定编译错误的快速方法是将以下内容放在源代码文件的顶部:

using System.Collections;

或者,您可以通过在声明IEnumerable时指定类型参数来使用Generic版本(您应该尽可能尝试这样做,因为它是类型安全的),如下所示:

IEnumerable<Car>
 IEnumerator<Car>

您可能还想阅读An Introduction to C# Generics

您似乎还有一些错误,但这些似乎可能来自复制和粘贴源的问题(特别是Garage不实现IEnumerable,通用或非通用版本,GetEnumerator在Program类上,而不是车库类).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读