小编典典

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

c#

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

我该如何实现?


阅读 705

收藏
2020-05-19

共1个答案

小编典典

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

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

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

如果它们在不同的命名空间中,则还需要AllMethodsusing语句中将的命名空间添加到caller.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
        }
    }
}

进一步阅读

2020-05-19