是否可以在派生类或任何其他类中调用抽象类的方法
是否可以在派生类或任何其他类中调用抽象类的方法。我的代码如下,我想在Program的Main方法中调用Abstr的Describe()
方法。 是否可以?如果答案是肯定的怎么办?
class Program
{
public void Main()
{
//I want to call the Describe() method here, how do i do that
Console.ReadLine();
}
}
public abstract class Abstr
{
public void Describe()
{
//do something
}
}
Is it possible to call method of an Abstract class in derived class or any other class. My code is below, I want to call Abstr's Describe()
method in Program's Main method.
Is it possible? if answer is yes how?
class Program
{
public void Main()
{
//I want to call the Describe() method here, how do i do that
Console.ReadLine();
}
}
public abstract class Abstr
{
public void Describe()
{
//do something
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您的方法不是静态的,因此您需要从该抽象类初始化一个变量并从中调用该方法。为此,您可以通过 concreate 类继承抽象类,然后调用该方法。请注意,抽象类无法初始化,抛出像
Abstr Abstr = new Abstr();
这样的构造函数是无效的。所以:Since your method is not static, you need to initialize a variable from that abstract class and call that method from it. To do that you may inherit the abstract class by concreate class and then call that method. Note that the abstract class can't be initialized throw a constructor like
Abstr abstr = new Abstr();
is not valid. So:您应该能够直接使用
Abstr.Describe()
。它是一个静态方法,因此抽象类并不重要。编辑
现在问题中的代码已被编辑,并且方法上的
static
关键字已被删除,该答案不再适用。You should be able to use
Abstr.Describe()
directly. It is a static method, so the class being abstract shouldn't matter.Edit
Now that the code in the question has been edited and the
static
keyword is removed on the methods, this answer does no longer apply.答:当然可以,只要它是公共的、受保护的(和同一个类或子类)或内部的(和同一个程序集)
答:当然,只要它是公共的或内部的(以及相同的程序集)
良好的链接:
http://agsmith.wordpress.com/2007/12/15/内部和保护/
A: Sure, as long as it's public, protected (and the same class or a subclass), or internal (and the same assembly)
A: Sure, as long as it's public or internal (and the same assembly)
Good link:
http://agsmith.wordpress.com/2007/12/15/internal-and-protected/
是的,可以使用代码:此处
这也适用于非静态方法
yes it is possible code : here
This works for non static method as well
致电编辑就足够了
:
原始帖子已更改,因此该答案无效。
问候。
It's enough to call
EDIT:
Original post was changed, so this answer is not valid.
Regards.
是的,只要子类型(以及想要调用该方法的代码)可以访问超类型中的方法定义。
这是一些示例代码。是否调用子类型或超类型中的方法定义取决于重写的定义方式:
Yes, so long as the method definition in the supertype is accessable to the subtype (and to the code that wants to invoke the method).
Here's some sample code. Whether the method definition in the subtype or supertype is invoked is dependent upon how the override is defined: