现在我有两个类allmethods.cs和caller.cs.
我在课堂上有一些方法allmethods.cs.我想写一个代码,caller.cs以便在中调用某个方法allmethods.
代码示例:
public class allmethods
public static void Method1()
{
// Method1
}
public static void Method2()
{
// Method2
}
class caller
{
public static void Main(string[] args)
{
// I want to write a code here to call Method2 for example from allmethods Class
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?任何帮助?
谢谢.
p.s*_*w.g 99
因为它Method2是静态的,所以你要做的就是这样调用:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
Run Code Online (Sandbox Code Playgroud)
如果它们位于不同的命名空间中,您还需要AllMethods在using语句中添加caller.cs 的命名空间.
如果要调用实例方法(非静态),则需要该类的实例来调用该方法.例如:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读