C# - 重定义一个接口的实现

时间:2021-07-28 17:04:25

using System;
using System.Collections.Generic;
using System.Text;

namespace MyTester
{
    public interface IStorable {
        void Read();
        void Write();
    }

public class Document:IStorable
    {
        public Document(String s) {
            Console.WriteLine("Createing Document with:{0}",s);       
        }

//实现接口类的Read方法并声明为虚方法,可以被子类重写
        public virtual void Read()
        {
            Console.WriteLine("Document Read Method for IStorable");
        }

//实现接口类的Write方法
        public void Write()
        {
            Console.WriteLine("Document Write Method for IStorable");
        }
    }

public class Note : Document {
        public Note(String s):base(s) {
            Console.WriteLine("Creating note with:{0}",s);
        }

//重写Document类的Read方法
        public override void Read()
        {
            Console.WriteLine("Overriding the Read method for Note");
        }

//Note重新创建的Write方法,只属于Note本身
        public new void Write() {
            Console.WriteLine("Implementing the Write method for Note!");
        }
    }

public class Tester {
        static void Main() {
            Document theNote = new Note("Test Note");
            IStorable isNote = theNote as IStorable;
            if (isNote != null) {
                isNote.Read();
                isNote.Write();
            }
            
            Console.WriteLine("\r\n");

theNote.Read();
            theNote.Write();

Console.WriteLine("\r\n");

Note note2 = new Note("Second Test");
            IStorable isNote2 = note2 as IStorable;
            if(isNote != null){
                isNote2.Read();
                isNote2.Write();
            }

Console.WriteLine("\r\n");

note2.Read();
            note2.Write();

Console.ReadLine();
        }
    }
}