因为Method2是静态的,你所要做的就是这样调用:
public class AllMethods
{
public static void Method2()
{
// code here
}
}
class Caller
{
public static void Main(string[] args)
{
AllMethods.Method2();
}
}
如果它们位于不同的命名空间中,您还需要AllMethods在语句中将命名空间添加到 caller.cs using。
如果你想调用一个实例方法(非静态),你需要一个类的实例来调用该方法。例如:
public class MyClass
{
public void InstanceMethod()
{
// ...
}
}
public static void Main(string[] args)
{
var instance = new MyClass();
instance.InstanceMethod();
}
更新
从 C# 6 开始,您现在还可以通过using static指令更优雅地调用静态方法来实现这一点,例如:
// AllMethods.cs
namespace Some.Namespace
{
public class AllMethods
{
public static void Method2()
{
// code here
}
}
}
// Caller.cs
using static Some.Namespace.AllMethods;
namespace Other.Namespace
{
class Caller
{
public static void Main(string[] args)
{
Method2(); // No need to mention AllMethods here
}
}
}
延伸阅读