【问题标题】:How to make method call another one in classes?如何让方法在类中调用另一个方法?
【发布时间】:2013-04-20 00:54:32
【问题描述】:

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

我怎样才能做到这一点?

【问题讨论】:

    标签: c# methods call


    【解决方案1】:

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

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

    如果它们位于不同的命名空间中,您还需要在 using 语句中将 AllMethods 的命名空间添加到 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
            }
        }
    }
    

    进一步阅读

    【讨论】:

    • 我非常感谢这个答案,对于像我这样的新手来说,要获得 +1 是一件很难的事情。
    • 这太棒了!谢谢。但是,在每次调用函数之前,如何在不使用 className 的情况下执行这些方法呢?我见过有人这样做。
    • @SJ10 我认为您指的是(相对)新的 using static 指令。请参阅我的更新答案。
    • @p.s.w.g 啊,是的,谢谢!这消除了我一直在阅读的代码的一些混乱。
    猜你喜欢
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多