C# virtual, base, override
2015-11-29 15:58
537 查看
先看这样一段代码:
namespace @virtual
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
}
class Program
{
static void Main(string[] args)
{
A p = new A();
p.print();
p = new a();
p.print();
Console.ReadKey();
}
}
}
output:
base
base
p调用了基类的同名方法,如果想使用子类的print()需要用virtual修饰基类的print()再在子类中override重写print(),那样才能调用派生类的方法
output:
base
derive
它达到的效果和下面的代码是一样的:
namespace @virtual
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
}
class Program
{
static void Main(string[] args)
{
A p = new A();
p.print();
a p1 = new a();
p1.print();
Console.ReadKey();
}
}
}
output:
base
derive
base则是对在派生类里对基类成员的访问。在基类数据成员或方法被子类同名成员隐藏的情况下,它能发挥巨大的作用。
namespace @base
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
public void fatherPrint()
{
base.print();
}
}
class Program
{
static void Main(string[] args)
{
a p1 = new a();
p1.fatherPrint();
p1.print();
Console.ReadKey();
}
}
}
output:
base
derive
namespace @virtual
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
}
class Program
{
static void Main(string[] args)
{
A p = new A();
p.print();
p = new a();
p.print();
Console.ReadKey();
}
}
}
output:
base
base
p调用了基类的同名方法,如果想使用子类的print()需要用virtual修饰基类的print()再在子类中override重写print(),那样才能调用派生类的方法
namespace @virtual { class A { public virtual void print() { Console.WriteLine("base"); } } class a :A{ public override void print() { Console.WriteLine("derive"); } } class Program { static void Main(string[] args) { A p = new A(); p.print(); p = new a(); p.print(); Console.ReadKey(); } } }
output:
base
derive
它达到的效果和下面的代码是一样的:
namespace @virtual
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
}
class Program
{
static void Main(string[] args)
{
A p = new A();
p.print();
a p1 = new a();
p1.print();
Console.ReadKey();
}
}
}
output:
base
derive
base则是对在派生类里对基类成员的访问。在基类数据成员或方法被子类同名成员隐藏的情况下,它能发挥巨大的作用。
namespace @base
{
class A
{
public void print()
{
Console.WriteLine("base");
}
}
class a :A{
public void print()
{
Console.WriteLine("derive");
}
public void fatherPrint()
{
base.print();
}
}
class Program
{
static void Main(string[] args)
{
a p1 = new a();
p1.fatherPrint();
p1.print();
Console.ReadKey();
}
}
}
output:
base
derive
相关文章推荐
- C#构造方法
- c#之再战委托事件多线程2_委托和事件结合降低模块低耦合
- C#小结(一)
- c#之再战委托事件多线程1_仅仅是委托
- C#中sealed关键字
- C#与C++的混合编程 之三 C++与C#的数据传递与类型转换
- C#与C++的混合编程 之二 使用非托管dll 导出标准函数
- 【C#】用组件的Anchor属性解决最大化组件的缩放问题
- C#与C++的混合编程 之一 方法介绍
- 【C#】文件选择对话框OpenFileDialog与下列列表ComboBox
- 【CS】——C#初识
- C#开篇
- WCF 之角色验证
- C#-高血压生活习惯数据模拟
- BC#64 4.Tree
- C#4.0之dynamic的使用
- C#程序从Excel表格中读取数据并进行处理
- C# 操作Excel
- C#—数据类型
- C#中的Contains与IndexOf的区别