1,常用接口及其定义
public interface IDisposable{ void Dispose(); } public interface IEnumerable}{ IEnumerator GetEnumerator(); } public interface IEnumerable<T>:IEnumerable{ IEnumerator GetEnumerator<T> GetEnumerator() } public interface ICollection<T>:IEnumerable<T>,IEnumerable { void Add(T item); void Clear(); Boolean Contains(T item); void CopyTo(T[] array,int32 arrayIndex); int32 Count{get;} Boolean IsReadOnly {get;}
}
- 接口继承:接口继承表示某类如果继承该接口,则必须实现该接口的继承接口的方法.
- 比如 ,必须实现这些方法.
public class MyClassForInterface<T> : ICollection<T> where T:class,new() { public int Count => throw new NotImplementedException(); public bool IsReadOnly => throw new NotImplementedException(); public void Add(T item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(T item) { throw new NotImplementedException(); } public void CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } public IEnumerator<T> GetEnumerator() { throw new NotImplementedException(); } public bool Remove(T item) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } }
2,当实现接口的时候,的一些结果
public class Base : IDisposable { public void Dispose()//实现接口函数,未加virutal,则默认是 virtual sealed---无法重载. { Console.WriteLine("Base's Dispose!"); } } public class Derived : Base, IDisposable { public new void Dispose()//new,关键字表明这是重新实现的Dispose方法.override...表明是重载的方法. { Console.WriteLine("Derived's Dispose!"); } } public static class CallBaseDerivedOfInterface { public static void CallBaseAndDerived() { Base b = new Base();//b的类型,和b的对象的类型都是Base; Derived d = new Derived();//d的类型和d的对象的类型都是Derived b.Dispose();//调用b的类型的Dispose d.Dispose();//调用d的类型的Dispose ((IDisposable)b).Dispose();//调用b的对象的类型的Dispose,Base.Dispose ((IDisposable)d).Dispose();//调用d的对象的类型的Dispose,Derived.Dispose b = new Derived();//b的类型是Base,b的对象的类型是Derived b.Dispose();//调用Base.Dispose ((IDisposable)b).Dispose();//调用b的对象的Dispose---Derived.Dispose } }
//结果
Base's Dispose!
Derived's Dispose!
Base's Dispose!
Derived's Dispose!
Base's Dispose!//----调用Base.Dispose
Derived's Dispose!//---调用Derived.Dispose
3,隐式和显式接口方法实现
public class SimpleType : IDisposable { public void Dispose() { Console.WriteLine("Dispose"); } }
则该类的类型的方法表里将包含:
- Object定义的所有虚实列方法
- IDisposeable定义的所有接口方法.Dispose();
- SimpleType 引入的新方法Dispose();
在本列中 和上列中,调用 b.Dispose()---则调用SimpleType 定义的Dispose()方法.
调用((IDispose)b).Dispose---调用的是接口的Dispose()方法--其指向上一个方法.
public class SimpleType : IDisposable { public void Dispose() { Console.WriteLine("Dispose"); } void IDisposable.Dispose()//显示的接口实现 { Console.WriteLine("IDispose.Dispose"); } }
SimpleType st = new SimpleType();
st.Dispose();
((IDisposable)st).Dispose();//只有显示的接口类型 才能够调用.
//
Dispose
IDispose.Dispose