簡體   English   中英

通過由基類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()方法(無論如何也不能重寫,因為PersonWrite()方法未標記為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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM