C#笔记(2)
二、Interface接口只能包含抽象成员,也就是说:接口不能有字段,不能有构造函数,不能提供方法实现。接口可以定义属性
(本质上是方法)协议。struct也可以实现接口。接口实现必须实现祖先接口的所有方法。
接口命名冲突,例如IDrawToForm和IDrawToPrinter都包含Draw()方法,这时候:
Class Octagon :IDrawToForm,IDrawToPrinter{ public void Draw(){…}}
如果有Octagon的对象oct,那么((IDrawToForm)oct).Draw()和(( IDrawToPrinter)oct).Draw()都是调用同一个实现,这时候可以使用显式接口实现语法:
class Octagon :IDrawToForm,IDrawToPrinter{ //注意,没有访问修饰符,因为必须是私有的 void IDrawToForm.Draw(){…} void IDrawToPrinter.Draw(){…}} A. IEnumerable和IEnumerator
任何支持GetEnumerator()方法的或者实现IEnumerable接口类型都可以通过foreach结构进行运算。
public interface IEnumerable{ IEnumerator GetEnumerator();}public interface IEnumerator{ bool MoveNext (); object Current { get;} void Reset ();} B. ICloneable
public interface ICloneable{ objectClone();}System.Object的MemberwiseClone()得到一个浅拷贝。
C. IComparable,IComparer
public interface IComparable{ int CompareTo(object o); }interface IComparer{ int Compare(object o1, object o2);}
Array.Sort(Alist),其中Alist里的成员必须实现IComparable接口, IComparer不是在要排序的类型中实现,而是在辅助类中实现的:
public class PetNameComparer : IComparer{ int IComparer.Compare(object o1, object o2) { Car t1 = (Car)o1; Car t2 = (Car)o2; return String.Compare(t1.PetName, t2.PetName); }}static void Main(string[] args){ ... Array.Sort(myAutoList, new PetNameComparer());}
三、 构造函数,static
class Motorcycle{ publicMotorcycle(string name) : this(0, name)//调用另一个构造函数 {}}
静态构造函数
class Motorcycle{ public static stringcompany//不能有访问修饰符,不能有参数,只有一个,只执行一次(在访问静态成员之前)// 执行在任何实例构造函数之前。 staticMotorcycle (){ company = “BMW”;}}
如果一个类定义成static,不能使用new创建对象,且只能包含static成员。
页:
[1]