質問

I am new to C# and I'm having a little problem with calling a function from the Main() method.

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

I get a compiler error in test();:

An object reference is required for the non-static field.

I don't quite understand these modifiers yet so what am I doing wrong?

What I really want to do is have the test() code inside Main() but it gives me an error when I do that.

役に立ちましたか?

解決 2

Just put all logic to another class

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

and

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

他のヒント

If you still want to have test() as an instance method:

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
    }
}

or rather make it static:

class Program
{
    static void Main(string[] args)
    {
        Test();
    }

    static void Test()
    {
        // I'm static
        // You can call me from another static method
    }
}

To get the info of a static method:

typeof(Program).GetMethod("Test", BindingFlags.Static);

The method must be static in order to call it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top