简体   繁体   English

如何在C#中的另一个方法中从同一类中调用一个方法?

[英]How to call a method from same class in another method in C#?

Now I am working with c# code that looks something like this 现在我正在使用看起来像这样的C#代码

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        //Do something
        Method1();
    }
}

Now what if I replace the code as: 现在,如果我将代码替换为:

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        //Do something
        MyClass.Method1();
    }
}

Now what is the difference in above 2 representations. 现在,以上两种表示形式有什么区别。 Is it the same or does it show some different working. 是相同的还是显示不同的工作方式。 Any help is appreciated. 任何帮助表示赞赏。

The second is just a longer version of the previous. 第二个只是前一个版本的较长版本。 If you are in the same class as the static method, you do not need to specify the class name, you can, but you don't need to (much like specifying this for instance methods). 如果您与静态方法位于同一类中,则可以不必指定类名,但是不必(与为实例方法指定this一样)。

Inside the class there is no difference but the difference comes when you try to invoke them from outside the class. 在类内部没有区别,但是当您尝试从类外部调用它们时会有所不同。 For instance method you need a instance of your class whereas for static method that's not required. 例如,实例方法需要类的实例,而对于静态方法则不需要。 But inside your class you can just say 但是在课堂上,你只能说

public class MyClass
{
    public static void Method1()
    {
        //Do something
    }

    public void Method2()
    {
        Method1();  //you don't have to qualify it
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM