关于c#中的虚拟类 [英] About Virtual Classes in c#
本文介绍了关于c#中的虚拟类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
在很多采访中,我面临一个小小的困惑。
我有两个类ChildClass和Base Class
Hi Guys,
In lot of interview I am facing a small confusion.
I am having two classes ChildClass and Base Class
class BaseClass
{
public virtual void Test()
{
Console.WriteLine("BaseClass:Test()");
}
}
class ChildClass : BaseClass
{
public override void Test()
{
Console.WriteLine("ChildClass:Test()");
}
}
现在我的问题是什么是虚拟课程的使用
Now My Questions is what is the use of virtual classes
ChildClass B = new ChildClass();
B.Test();
BaseClass C = new ChildClass();
C.Test();
我可以在heritence中访问Test()函数而且没有继承权也可以...那么继承的用途是什么。
请澄清我。
温馨的问候,
阿里
I can access Test() function with in heritence and without inheritence also na... Then what is the use of Inheritence.
Please clarify me.
Warm Regards,
Ali
推荐答案
你可以扩展一些基础子类中的功能。
http:// www .csharp-station.com / Tutorials / lesson08.aspx [ ^ ]
祝你好运!
you can extend some base functionality in a subclass.
http://www.csharp-station.com/Tutorials/lesson08.aspx[^]
good luck!
诀窍是你可以使用对基数的引用用于引用继承的类,并且在运行时,使用该引用调用虚函数时,将调用继承类中的重写函数。请考虑以下代码:
The trick is that you can use a reference to the base class to reference an inherited one and, at runtime, when you call a virtual function using that reference, the overridden one in the inherited class is called. Consider the code below:
class BaseClass
{
public virtual void Test()
{
Console.WriteLine("BaseClass:Test()");
}
}
class ChildClassA : BaseClass
{
public override void Test()
{
Console.WriteLine("ChildClassA:Test()");
}
}
class ChildClassB : BaseClass
{
public override void Test()
{
Console.WriteLine("ChildClassB:Test()");
}
}
现在假设您写的是这样的:
Now suppose that you write something like this:
BaseClass obj = new ChildClassA();
obj.Test();
obj = ChildClassB();
obj.Test()
你得到的输出是这样的:
The output that you get is something like this:
ChildClassA:Test()
ChildClassB:Test()
没有这样的作为虚拟课程
的事情。
当然你必须把课程与方法混淆。
请阅读一些非常基本的课程关于面向对象编程的文档。
There is no such thing as avirtual class
.
Surely you must confuse classes with methods.
Please read some very basic documentation about object orientated programming.
这篇关于关于c#中的虚拟类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文