是否可以在派生类或任何其他类中调用Abstract类的方法

Pra*_*eep 1 c# oop abstract-class

是否可以在派生类或任何其他类中调用Abstract类的方法.我的代码如下,我想Describe()在Program的Main方法中调用Abstr的方法.可能吗?如果答案是肯定的?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

Jal*_*aid 10

由于您的方法不是静态的,因此需要从该抽象类初始化变量并从中调用该方法.为此,您可以通过concreate类继承抽象类,然后调用该方法.注意,抽象类不能初始化抛出一个像Abstr abstr = new Abstr();无效的构造函数.所以:

public abstract class Abstr
{
    public void Describe()
    {
        //do something
    }
}

public class Concrete : Abstr
{
   /*Some other methods and properties..*/ 
}

class Program
{
    public void Main()
    {
        Abstr abstr = new Concrete();
        abstr.Describe();
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Ramhound:我想展示如何初始化\ use`Abstr`实例. (2认同)