【问题标题】:Call function from Main()从 Main() 调用函数
【发布时间】:2014-04-10 19:38:44
【问题描述】:

我是 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(); 中收到编译器错误:

非静态字段需要对象引用。

我还不太了解这些修饰符,所以我做错了什么?

我真正想要做的是在Main() 中包含test() 代码,但是当我这样做时它会给我一个错误。

【问题讨论】:

  • 正如错误信息告诉你的,你需要一个对象引用来调用一个非静态成员。所以创建一个对象引用。
  • 来自方法?怎么可能从一个方法中创建一个对象?还是您的意思是我必须将 test() 放入一个新类中?
  • 您需要一个定义该方法的类型的实例,才能调用该类型的实例方法。我敢肯定,在 obj-c 中也是如此。
  • 为什么要投反对票?我没有做错任何事!
  • 你在问这个问题之前甚至没有做基础研究。做一些简单的事情,比如对错误消息执行网络搜索,可以得到大量关于你做错了什么的信息。

标签: c# static-methods instance-methods


【解决方案1】:

只需将所有逻辑放到另一个类中

 class Class1
    {
        public void test()
        {
            MethodInfo mi = this.GetType().GetMethod("test2");
            mi.Invoke(this, null);
        }
        public void test2()
        {
            Console.Out.WriteLine("Test2");
        }
    }

和

  static void Main(string[] args)
        {
            var class1 = new Class1();
            class1.test();
        }

【讨论】:

    【解决方案2】:

    如果您仍想将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);
    

    【讨论】:

      【解决方案3】:

      方法必须是静态的才能调用它。

      【讨论】:

      • 这就是我不能在静态方法中使用 MethodInfo 的问题。
      • 方法不是静态的。
      • @Arbitur 静态方法的类型在编译时总是已知的;无需动态获取。
      猜你喜欢
      • 1970-01-01
      • 2013-01-12
      • 1970-01-01
      • 2013-05-28
      • 2016-07-14
      • 1970-01-01
      • 1970-01-01
      • 2013-06-23
      • 2016-06-13
      相关资源
      最近更新 更多