gpt4 book ai didi

c# - 通过基类c#实现的接口(interface)调用类的方法

转载 作者:行者123 更新时间:2023-11-30 14:37:49 25 4
gpt4 key购买 nike

我有这段代码,但我就是看不懂。

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() 方法(无论如何您不能,因为 PersonWrite() 方法未标记为 virtual)。由于您是通过 IStoreable 调用它,因此 IStoreable 接口(interface)没有任何内容将它链接到 Student 类。由于 Write() 未标记为 virtual,因此此函数的多态性不适用。

关于c# - 通过基类c#实现的接口(interface)调用类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8841792/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com