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

本文关键字:方法 另一个 调用 何使 | 更新日期: 2023-09-27 18:10:52

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

我怎么才能做到呢?

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

因为Method2是静态的,所以您所要做的就是像这样调用:

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

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

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

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

进一步阅读

    静态类和静态类成员(c#编程指南)
  • 方法(c#编程指南)
  • using static指令(c# Reference)