为什么我不选择抽象?声明类成员虚拟有哪些限制?只能将方法声明为虚拟?
小智 10
抽象方法或属性(可以是虚拟的或抽象的)只能在抽象类中声明,并且不能有主体,即您不能在抽象类中实现它.
虚方法或属性必须具有正文,即必须提供实现(即使正文为空).
如果有人想要使用您的抽象类,他将必须实现一个继承自它的类并显式实现抽象方法和属性,但可以选择不覆盖虚拟方法和属性.
例如:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)