我是 C# 新手,在从 Main()
方法调用函数时遇到了一些问题。
class Program
{
static void Main(string[] args)
{
test();
}
public void test()
{
MethodInfo mi = this.GetType().GetMethod("test2");
mi.Invoke(this, null);
}
public void test2()
{
Console.WriteLine("Test2");
}
}
我在 test();
中遇到编译器错误:
An object reference is required for the non-static field.
我还不太了解这些修饰符,所以我做错了什么?
我真正想做的是将 test()
代码放在 Main()
中,但是当我这样做时它会给我一个错误。
最佳答案
如果您仍想将 test()
作为实例方法:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.test();
}
void Test()
{
// I'm NOT static
// I belong to an instance of the 'Program' class
// You must have an instance to call me
}
}
或者更确切地说,让它成为静态的:
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
// I'm static
// You can call me from another static method
}
}
获取静态方法的信息:
typeof(Program).GetMethod("Test", BindingFlags.Static);
关于c# - 从 Main() 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22997465/