![](/img/trans.png)
[英]Prevent calling base class implemented interface method in the derived class C#
[英]Calling a method of a class through the interface implemented by the base class c#
我有这段代码,但我听不懂。
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()`?
new
关键字指示您不打算覆盖基类的Write()
方法(无论如何也不能重写,因为Person
的Write()
方法未标记为virtual
)。 由于您是通过IStoreable
调用它的,所以没有任何关于IStoreable
接口将其链接到Student
类的信息。 由于Write()
未标记为virtual
,因此该函数的多态性不适用。
使该人的写方法成为虚拟。 当您将其标记为新时,它不会充当继承的方法。 当您将方法标记为虚拟时,意味着您提供了一个实现,并且可以由子类覆盖它。 抽象需要您实现一种方法(仅需多花一点时间)。
class Person : IStoreable {
public virtual void Read() { Console.WriteLine("Person.Read()"); }
public virtual void Write() { Console.WriteLine("Person.Write()"); }
}
class Student : Person {
public override void Read() { Console.WriteLine("Student.Read()"); }
public override void Write() { Console.WriteLine("Student.Write()"); }
“当用作修饰符时,new关键字显式隐藏从基类继承的成员”
作为IStoreable的Student无法看到Student.Write方法,因为未从基类Person中覆盖它。 为什么不将其标记为虚拟,为什么要使用new关键字隐藏基类的实现?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.