转载-区分C#中的Abstract函数和Virtual函数
发现很多朋友对于C#中的Abstract和Virtual函数区分得不是很清楚,下面我通过两段代码让大家看看这两者之间到底有什么区别~~
开发环境: VS.net 2005
使用方法: 用以下代码覆盖program.cs中的代码,然后run即可
第一段代码: Abstract的用法
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication3
{
public abstract class Book
{
//抽象方法,不含主体,抽象方法所在类必须为抽象类,派生类必须实现该方法
public abstract void Introduce();
}
public interface iBook
{
}
public class JavaBook : Book
{
//实现抽象方法,必须实现,必须添加override关键字
public override void Introduce()
{
Console.WriteLine("I'm Java");
}
// // Compile Error
// public void Introduce()
// {
// Console.WriteLine("I'm Java");
// }
}
public class test
{
public test()
{
JavaBook javaBook = new JavaBook();
javaBook.Introduce(); //将调用JavaBook中Introduce()
Book book = new JavaBook();
book.Introduce(); //将调用JavaBook中Introduce()
}
public static void Main()
{
test t = new test();
}
}
}
第二段代码: Virtual的用法以及override的用法
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication2
{
public abstract class Book
{
public virtual void Introduce()
{
Console.WriteLine("I'm book");
}
public virtual void SayHi()
{
Console.WriteLine("Hi, I'm book");
}
}
public class JavaBook : Book
{
public override void Introduce()
{
Console.WriteLine("I'm Java");
}
//注意,此方法没有override父类的方法
public void SayHi()
{
Console.WriteLine("Hi, I'm Java");
}
}
public class test
{
public test()
{
JavaBook javaBook = new JavaBook();
Book book = new JavaBook();
javaBook.Introduce(); //将调用JavaBook中Introduce()
book.Introduce(); //将调用JavaBook中Introduce()
javaBook.SayHi(); //将调用JavaBook中SayHi()
book.SayHi(); //将调用Book中SayHi()
}
public static void Main()
{
test t = new test();
}
}
}
第三段代码: new的用法
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication4
{
public abstract class Book
{
public void Introduce()
{
Console.WriteLine("I'm book");
}
public void SayHi()
{
Console.WriteLine("Hi, I'm book");
}
}
public class JavaBook : Book
{
// 没有加new,但C#默认行为会加上new
public void Introduce()
{
Console.WriteLine("I'm Java");
}
// 显式加上new,跟不加new实际效果一样,只是加new之后会消除compile warning
public new void SayHi()
{
Console.WriteLine("Hi, I'm Java");
}
}
public class test
{
public test()
{
JavaBook javaBook = new JavaBook();
Book book = new JavaBook();
javaBook.Introduce(); //将调用JavaBook中Introduce()
javaBook.SayHi(); //将调用JavaBook中SayHi()
book.Introduce(); //将调用Book中Introduce()
book.SayHi(); //将调用Book中SayHi()
}
public static void Main()
{
test t = new test();
}
}
}