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();
}