5

私は 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();ます。

非静的フィールドにはオブジェクト参照が必要です。

これらの修飾子をまだよく理解していないので、何が間違っているのでしょうか?

私が本当にやりたいことは、test()コードを内部に入れることですがMain()、それを行うとエラーが発生します。

4

3 に答える 3

7

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);
于 2014-04-10T19:44:31.830 に答える
7

すべてのロジックを別のクラスに配置するだけです

 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();
        }
于 2014-04-10T19:43:02.770 に答える
1

メソッドを呼び出すには、メソッドが静的である必要があります。

于 2014-04-10T19:39:13.547 に答える