how to call static method inside non static method

2020-04-21 06:45发布

问题:

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