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

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

问题描述

现在我有两个类 AllMethods.cs caller.cs

我在类中的一些方法 AllMethods.cs 。我想写在 caller.cs A code,以调用在 AllMethods.cs 。

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

在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? Any Help?

感谢。

推荐答案

由于该方法2 是静态的,你所要做的就是调用是这样的:

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

如果他们是在不同的命名空间,你还需要将 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();
}

进一步阅读

  • Static Classes and Static Class Members (C# Programming Guide)
  • Methods (C# Programming Guide)

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

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