Arb*_*tur 2 c# static-methods instance-methods
我是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");
}
}
Run Code Online (Sandbox Code Playgroud)
我在编译错误test();:
非静态字段需要对象引用.
我还不太了解这些修饰语,所以我做错了什么?
我真正想做的是将test()代码放在里面,Main()但是当我这样做时它会给我一个错误.
把所有逻辑都放到另一个班级
class Class1
{
public void test()
{
MethodInfo mi = this.GetType().GetMethod("test2");
mi.Invoke(this, null);
}
public void test2()
{
Console.Out.WriteLine("Test2");
}
}
Run Code Online (Sandbox Code Playgroud)
和
static void Main(string[] args)
{
var class1 = new Class1();
class1.test();
}
Run Code Online (Sandbox Code Playgroud)
如果您仍然想拥有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
}
}
Run Code Online (Sandbox Code Playgroud)
或使其静态:
class Program
{
static void Main(string[] args)
{
Test();
}
static void Test()
{
// I'm static
// You can call me from another static method
}
}
Run Code Online (Sandbox Code Playgroud)
要获取静态方法的信息:
typeof(Program).GetMethod("Test", BindingFlags.Static);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21479 次 |
| 最近记录: |