how to call static method inside non static method in c#

こ雲淡風輕ζ 提交于 2019-12-02 13:59:36

问题


how to call static method inside non static method in c# ?

Interviewer gave me scenario :

class class1
{

    public static void method1(){}

    public void method2()
    {
        //call method1()
    }

How can we do it


回答1:


A normal practice is to call static method with class name.

See: Static Classes and Static Class Members (C# Programming Guide)

The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created.

So your call would be like:

class1.method1();

But it is not necessary

You can call the static method without class name like:

method1();

But you can only do that inside the class which holds that static method, you can't call static method without class name outside of that class.




回答2:


class1.method1();

Same as you'd call any other static method

Apparently (as Selman22 pointed out) - the classname isn't necessary.

So

method1();

would work just as well




回答3:


if you call the method in the some class you just call it like this

    public void method2()
    {
        method1();  

    }

but if it should been called from another class you have to precede it with the name of the class

public void method2()
        {
            class1.method1();  

        }



回答4:


You type the method name out, and then compile and run it:

class class1
{
    public static void method1(){}

    public void method2()
    {
        method1()
    }
}


来源:https://stackoverflow.com/questions/21532756/how-to-call-static-method-inside-non-static-method-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!