如何使方法在类中调用另一个? [英] How to make method call another one in classes?

查看:43
本文介绍了如何使方法在类中调用另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

代码示例:

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是静态的,因此您要做的就是这样调用:

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

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

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

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

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

如果要调用实例方法(非静态),则需要类的实例才能对其进行调用.例如:

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();
}

更新

从C#6开始,您现在还可以使用using static指令来实现此目的,以更优雅地调用静态方法,例如:

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

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

进一步阅读

  • Static Classes and Static Class Members (C# Programming Guide)
  • Methods (C# Programming Guide)
  • using static directive (C# Reference)

这篇关于如何使方法在类中调用另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆