Having trouble calling a public method in a static method

南笙酒味 提交于 2019-12-11 23:36:46

问题


I'm really sorry because this is probably a very newbish question, but I can't find an answer to this anywhere. I'm confused on how to call the function DoStuff below

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public void DoStuff()
        {
            Console.WriteLine("I'm doing something...");
        }
        static void Main(string[] args)
        {
            DoStuff();
        }
    }
}

回答1:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public static void DoStuff()
        {
            Console.WriteLine("I'm doing something...");
        }
        static void Main(string[] args)
        {
            DoStuff();
        }
    }
}

C# is an object oriented programming language which means that every member within a class. Since the static method init before normal method , you should define DoStuff as a static method so that it can be call within Main method. When the class has been created, the static member already init in the computer's memory, however, the non-static member will waiting to the instance of the class. In that case, the static member belong to the whole class and the non-static belong to an instance of a class. So you can use ClassName.StaticMember to call StaticMember and you need a real instance of a class to call non-staticMember. just like: new Program().DoStuff() if the DoStuff is non-static method




回答2:


public void is an Instance method. There is an implicit, hidden parameter to the function called this.

public static void is a Static method. There is no implicit this parameter.

Your DoStuff method does not use the this reference, so change it to public static void DoStuff.




回答3:


do a MSDN Google search on the Instance Method vs Static Method Static and instance methods

change the following:

public void DoStuff() 

to public

public static void DoStuff() 

If you want to call a public method inside a static void Main, you need to create a new instance of Program like this

static void Main(string[] args)
{
     var prg = new Program(); 
     prg.DoStuff();
}



回答4:


Create an instance of Program:

static void Main(string[] args)
{
    new Program().DoStuff();
}


来源:https://stackoverflow.com/questions/35568120/having-trouble-calling-a-public-method-in-a-static-method

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