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

前端 未结 4 903
隐瞒了意图╮
隐瞒了意图╮ 2021-01-24 05:58

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

Interviewer gave me scenario :

class class1
{

    pub         


        
相关标签:
4条回答
  • 2021-01-24 06:41

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

    class class1
    {
        public static void method1(){}
    
        public void method2()
        {
            method1()
        }
    }
    
    0 讨论(0)
  • 2021-01-24 06:56
    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

    0 讨论(0)
  • 2021-01-24 06:59

    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.

    0 讨论(0)
  • 2021-01-24 07:00

    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();  
    
            }
    
    0 讨论(0)
提交回复
热议问题