接口,深入接口,索引器,foreach本质

1.接口

接口代表一种能力,实现该接口的类和接口没有继承关系

接口是用来实现的,类是用来继承的。

 public interface IFly
    {
        string Say(string str);
    }
类Blan继承 接口类Ifly并重写方法Say()
public class Blan:IFly { public string Say(string str) { Console.WriteLine("小鸟飞呀飞"); return "hhh"; } } public class Plane:IFly { public string Say(string str) { Console.WriteLine("飞机飞呀飞"); return "hh"; } } static void Main(string[] args) { IFly[] iflt={new Plane(),
new Blan()


};
foreach (IFly item in iflt) { Console.WriteLine(item.Say("呵呵哈哈哈")); } Console.ReadLine();
 接口可以实现多继承,弥补单继承的缺陷。
public interface IFly { void IFlys(); } public interface IEat { void Eat(); } public class Eats:IFly,IEat { void IFly.IFlys() { Console.WriteLine(""); } void IEat.Eat() { Console.WriteLine(""); } }

C#中的类成员可以是任意类型,包括数组和集合。当一个类包含了数组和集合成员时,索引器将大大简化对数组或集合成员的存取操作。

定义索引器的方式与定义属性有些类似,其一般形式如下:

[修饰符] 数据类型 this[索引类型 index]

{

    get{//获得属性的代码}                                             

    set{ //设置属性的代码}

  }

 public class Student
    {
       private string[] name=new string[2];
       public string this[int index]
       {
           get { return name[index]; }
           set { name[index] = value; }
       }
    }
 static void Main(string[] args)
        {
        Student stu = new Student();
            stu[0] = "张三";
            stu[1] = "李四";
            Console.WriteLine(stu[0]);
            Console.ReadLine();
}        

Foreach原理:

 本质:实现了一个IEnumerable接口

为什么数组和集合可以使用foreach遍历?

解析:因为数组和集合都实现了IEnumerable接口,该接口中只有一个方法,GetEnumerator()

MyCollection类
 public class MyCollection:IEnumerable
    {
       ArrayList list = new ArrayList();
       public void Add(object o)
       {
           list.Add(o);
       }
        public IEnumerator GetEnumerator()
        {
            return new MyIEnumerator(list);
        }
    }
MyIEnumerator类
public class MyIEnumerator : IEnumerator
    {
        ArrayList list = new ArrayList();
        public MyIEnumerator(ArrayList mylist)
        {
            list = mylist;
        }
        private int i = -1;
        public object Current
        {
            get { return list[i]; }
        }

        public bool MoveNext()
        {
            bool falg = false;
            if (i<list.Count-1)
            {
                i++;
                falg = true;
            }
            return falg;
        }

        public void Reset()
        {
            i = -1;
        }
    }
static void Main(string[] args)
        {
//如果想让一个自定义的类型可以使用foreach循环进行遍历,必须实现Ienumerable接口
            MyCollection list = new MyCollection();
            list.Add("0");
            list.Add("1");
            foreach (object item in list)
            {
                Console.WriteLine(item);
            }
            ArrayList lists = new ArrayList();
            foreach (object item in lists)
            {
                
            }
            Console.ReadLine();
}
原文地址:https://www.cnblogs.com/s1294/p/5387161.html