關鍵字是用來決定哪些成員要使用子類別中的定義
// A a = new B(); //virtuall - new example
//
// A -------------> print (Call A)
// |
// -------------> B print (Call B)
//
namespace virtual_new
{
public class A
{
public virtual void print() { Console.WriteLine("Call A"); } // virtual here is not necessary!
}
public class B : A
{
public new void print() { Console.WriteLine("Call B"); }
}
public class Program
{
public static void Main(string[] args)
{
A a = new B();
a.print(); // Output: Call A
}
}
}
// A a = new B(); //virtual - override example
//
// A print (Call A)
//
// -------------> B -------------> print (Call B)
//
namespace virtual_override
{
public class A
{
public virtual void print() { Console.WriteLine("Call A"); } //virtual here is not necessary!
}
public class B : A
{
public override void print() { Console.WriteLine("Call B"); }
}
public class Program
{
public static void Main(string[] args)
{
A a = new B();
a.print(); // Output: Call B
}
}
}
沒有留言:
張貼留言