如何在类中使一个方法调用另一个方法?

73

现在我有两个类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
    }
}

我该如何实现这个目标?

1个回答

128

由于 Method2 是静态的,所以您只需像这样调用:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

如果它们在不同的命名空间中,您还需要在caller.cs中的using语句中添加AllMethods的命名空间。

如果您想调用实例方法(非静态方法),则需要一个类的实例来调用该方法。例如:

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

更多阅读


2
我非常感激这个答案,对于像我这样的新手来说,这是一件很难理解的事情 +1。 - Neil Meyer
太好了!谢谢。但是我如何在每次调用函数之前都不使用className来执行这些方法呢?我看到有人这样做过。 - SJ10
1
@SJ10 我认为你指的是(相对较新的)using static指令。请查看我的更新答案。 - p.s.w.g
@p.s.w.g 哦,是的,谢谢!这解决了我一直在阅读代码时的一些困惑。 - SJ10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接