简体   繁体   中英

How can be call the method from another class inherited

How can be call the method from another class inherited

let's see my code please:

class Program : classA
{
    static void Main(string[] args)
    {
        // how i can call method ToDo without create an instance like below
        //classA c = new classA();
        //c.ToDo();
        Console.ReadLine();
    }
}
class Program2 : classB
{
    static void Main(string[] args)
    {
        // how i can call method ToDo
        //ToDo()
        Console.ReadLine();
    }
}

public abstract class classB
{
    public void ToDo()
    {
        Console.WriteLine("classB");
    }
}
public class classA
{
    public void ToDo()
    {
        Console.WriteLine("classA");
    }
}

how i can call the method in Either way, please help me.

There are a couple ways to do what you want to do (they're kind of similar or even the same). One way is to create a class with a static method:

public class classA
{
    public static void ToDo()
    {
        Console.WriteLine("classA");
    }
}

then call it like:

classA.ToDo();

Another way is to add another static method to the class that contains Main:

class Program2 : classB
{
    static void Main(string[] args)
    {
        ToDo()
        Console.ReadLine();
    }

    static void Todo()
    {
        // do stuff here
    }
}

If u want to call ToDo() function into [class Program : classA] and [class Program : classB] Without creating Instance. U have to Define ToDo() function as static, then u can call this method with class name in anywhere. public static void ToDo(){}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM