mardi 8 septembre 2015

How to invoke a non static method by reflection

I'm trying to understand the reflection C#, specifically loading a third-party dll in my program. I created a simple dll:

namespace testclass
{
    public class Class1
    {
        private string f;
        public string f1 { get; set; }
    }

    public class Class2
    {
        public static int f2 = 0;
        public static string f1 { get; set; }

        static Class2()
        {
            Console.WriteLine("1st string");
        }

        public  void runme()
        {
            Console.WriteLine("2nd string");       
        }
    }
}

And load it to my program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

class program
{
   static void Main()
    {    
        Assembly assembly;
        assembly = Assembly.LoadFrom(@"D:\user\ClassLibrary1.dll");
        var exporttypes = assembly.GetExportedTypes();
        foreach (var types in exporttypes)
        {
            var fields = types.GetFields();
            foreach (var fi in fields)
            {
                if (fi.Name == "f2")
                {
                    fi.SetValue(exporttypes, 2);
                }
            }
            var m1 = types.GetMethods();
            for (int i = 0; i < m1.Length; i++)
            {
                if (m1[i].Name == "runme")
                {
                    m1[i].Invoke(types, null);
                }
            }
        }

        Console.ReadKey();
    }
}

The problem is that when you try to call the method 'runme', the compiler gives an exception if 'runme' is not static. I would like to understand that in this case you need to pass as the first argument to invoke





Aucun commentaire:

Enregistrer un commentaire