C# 如何让方法在类中调用另一个方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16226444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:27:20  来源:igfitidea点击:

How to make method call another one in classes?

c#methodscall

提问by Mina Hafzalla

Now I have two classes allmethods.csand caller.cs.

现在我有两个类allmethods.cscaller.cs.

I have some methods in class allmethods.cs. I want to write code in caller.csin order to call a certain method in the allmethodsclass.

我在课堂上有一些方法allmethods.cs。我想编写代码caller.cs以便调用类中的某个方法allmethods

Example on code:

代码示例:

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

How can I achieve that?

我怎样才能做到这一点?

采纳答案by p.s.w.g

Because the Method2is static, all you have to do is call like this:

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

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

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

If they are in different namespaces you will also need to add the namespace of AllMethodsto caller.cs in a usingstatement.

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

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

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

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

更新

As of C# 6, you can now also achieve this with using staticdirective to call static methods somewhat more gracefully, for example:

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

Further Reading

进一步阅读