public interface System.IComparable { int CompareTo(object o); }
public class TestCls: IComparable { public TestCls() { } private int _value; public int Value { get { return _value; } set { _value = value; } } public int CompareTo(object o) { //使用as模式进行转型判断 TestCls aCls = o as TestCls; if (aCls != null) { //实现抽象方法 return _value.CompareTo(aCls._value); } } }
abstract public class Animal { //定义静态字段 static protected int _id; //定义属性 public abstract static int Id { get; set; } //定义方法
public abstract void Eat(); //定义索引器 public string this[int i] { get; set; }
/// /// 实现抽象类 ///
public class Dog: Animal { public static override int Id { get {return _id;} set {_id = value;} } public override void Eat() { Console.Write("Dog Eats.") } }
public abstract class Animal { protected string _name; //声明抽象属性 public abstract string Name { get; }
//声明抽象方法
public abstract void Show();
//实现一般方法
public void MakeVoice() { Console.WriteLine("All animals can make voice!"); } }
2. 定义接口
public interface IAction { //定义公共方法标签 void Move(); }
3. 实现抽象类和接口
public class Duck : Animal, IAction { public Duck(string name) { _name = name; } //重载抽象方法
public override void Show() { Console.WriteLine(_name + " is showing for you."); }
//重载抽象属性
public override string Name { get { return _name;} }
//实现接口方法
public void Move() { Console.WriteLine("Duck also can swim."); } }
public class Dog : Animal, IAction { public Dog(string name) { _name = name; } public override void Show() { Console.WriteLine(_name + " is showing for you."); }
public override string Name { get { return _name; }
}
public void Move() { Console.WriteLine(_name + " also can run."); } }
4. 客户端实现
public class TestAnmial { public static void Main(string [] args) { Animal duck = new Duck("Duck"); duck.MakeVoice(); duck.Show(); Animal dog = new Dog("Dog"); dog.MakeVoice(); dog.Show(); IAction dogAction = new Dog("A big dog"); dogAction.Move(); } }