c# - 从 Main() 调用函数

标签 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");
    }
}

我在 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/

相关文章:

ruby - Swift 实例 vs 类方法加上类继承

python - 如何将一个类的实例方法 monkeypatch 到另一个类的实例方法?

node.js - 我可以让 Mongoose 文档从实例方法中删除自身吗?

c# - 为什么所有内容都打印在同一行上,即使我添加了 crlfs?

c# - 统一网格作为 ItemsControl 中所有项目的面板模板,第一个除外

java - 静态内部类和类的静态成员共享同名?

java - 无法从静态上下文引用非静态方法 "getActivity"

c# - 如何在 .NET Core 中修改文件访问控制

c# - typescript 中带有 Web Api 和 AngularJS 的 SPA 示例

具有可变类名和命名空间的 PHP 静态方法调用