我有这段代码,但我就是理解不了它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1 {
interface IStoreable {
void Read();
void Write();
}
class Person : IStoreable {
public virtual void Read() { Console.WriteLine("Person.Read()"); }
public void Write() { Console.WriteLine("Person.Write()"); }
}
class Student : Person {
public override void Read() { Console.WriteLine("Student.Read()"); }
public new void Write() { Console.WriteLine("Student.Write()"); }
}
class Demo {
static void Main(string[] args) {
Person s1 = new Student();
IStoreable isStudent1 = s1 as IStoreable;
// 1
Console.WriteLine("// 1");
isStudent1.Read();
isStudent1.Write();
Student s2 = new Student();
IStoreable isStudent2 = s2 as IStoreable;
// 2
Console.WriteLine("// 2");
isStudent2.Read();
isStudent2.Write();
Console.ReadKey();
}
}
}
我原以为无论哪种情况下,Student.Write()
都会被调用,但结果让我感到困惑:
// 1
Student.Read()
Person.Write()
// 2
Student.Read()
Person.Write()
为什么会调用
Person.Write()
而不是'Student.Write()`呢?