在静态方法中调用公共方法时遇到麻烦 [英] Having trouble calling a public method in a static method
问题描述
我真的很抱歉,因为这可能是一个非常新奇的问题,但是我在任何地方都找不到答案. 我对如何调用下面的函数DoStuff感到困惑
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();
}
}
}
推荐答案
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#是一种面向对象的编程语言,这意味着类中的每个成员.由于静态方法是在普通方法之前初始化的,因此应将DoStuff定义为静态方法,以便可以在Main方法中调用它.创建类后,静态成员已经在计算机的内存中初始化,但是,非静态成员将等待该类的实例.在这种情况下,静态成员属于整个类,而非静态成员属于一个类的实例.因此,您可以使用ClassName.StaticMember调用StaticMember,并且需要一个类的真实实例才能调用non-staticMember.就像:如果DoStuff是非静态方法,则为new Program().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
这篇关于在静态方法中调用公共方法时遇到麻烦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!