当应一类成员声明为虚函数(C#)/可重写(VB.NET)? [英] When should a class member be declared virtual (C#)/Overridable (VB.NET)?
问题描述
为什么不我选择抽象?什么是限制声明一个类成员的虚拟?只能方法声明为虚函数?
Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?
推荐答案
这是抽象方法或属性(都可以是虚拟的或抽象的)只能在抽象类中声明的,不能有身体,也就是你无法实现它在你的抽象类。
An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class.
一个虚拟的方法或属性必须有一个机构,即你必须提供一个实现(即使身体是空的)。
A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty).
如果有人想用你的抽象类,他将要实现一个类继承自它并明确实现抽象方法和属性,但可以选择不重写虚方法和属性。
If someone want to use your abstract class, he will have to implement a class that inherits from it and explicitly implement the abstract methods and properties but can chose to not override the virtual methods and properties.
例:
using System;
using C=System.Console;
namespace Foo
{
public class Bar
{
public static void Main(string[] args)
{
myImplementationOfTest miot = new myImplementationOfTest();
miot.myVirtualMethod();
miot.myOtherVirtualMethod();
miot.myProperty = 42;
miot.myAbstractMethod();
}
}
public abstract class test
{
public abstract int myProperty
{
get;
set;
}
public abstract void myAbstractMethod();
public virtual void myVirtualMethod()
{
C.WriteLine("foo");
}
public virtual void myOtherVirtualMethod()
{
}
}
public class myImplementationOfTest : test
{
private int _foo;
public override int myProperty
{
get { return _foo; }
set { _foo = value; }
}
public override void myAbstractMethod()
{
C.WriteLine(myProperty);
}
public override void myOtherVirtualMethod()
{
C.WriteLine("bar");
}
}
}
这篇关于当应一类成员声明为虚函数(C#)/可重写(VB.NET)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!