Invoke method by MethodInfo

前端 未结 3 899
孤街浪徒
孤街浪徒 2020-12-18 02:09

I want to invoke methods with a certain attribute. So I\'m cycling through all the assemblies and all methods to find the methods with my attribute. Works fine, but how do I

3条回答
  •  心在旅途
    2020-12-18 02:43

    Non-static methods are instance specific so you must instantiate the class to invoke the method. If you have the ability to change the code where it is defined and the method doesn't require itself to be part of an instance (it doesn't access or modify any non-static properties or methods inside the class) then best practice would be to make the method static anyway.

    Assuming you can't make it static then the code you need is as follows:

        foreach (Type t in types)
        {
                object instance = Activator.CreateInstance(t);
    
                MethodInfo[] methods = t.GetMethods();
                foreach (MethodInfo method in methods)
                {                    
                    method.Invoke(instance, params...);    
                }
        }
    

提交回复
热议问题