[英]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: 另一种方法是向包含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. 如果您要在不创建实例的情况下将ToDo()函数调用到[class Program:classA]和[class Program:classB]中。 U have to Define ToDo() function as static, then u can call this method with class name in anywhere.
您必须将ToDo()函数定义为静态,然后您可以在任何地方使用类名调用此方法。
public static void ToDo(){}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.