65

现在我有两个班级allmethods.cscaller.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
    }
}

我怎样才能做到这一点?

4

1 回答 1

116

因为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
        }
    }
}

延伸阅读

于 2013-04-25T23:39:13.517 回答