Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

c# - Invoke method by MethodInfo

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 invoke a certain method when I only got it's MethodInfo.

AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
foreach (Assembly a in ass)
{
    types = a.GetTypes();
    foreach (Type t in types)
    {
        MethodInfo[] methods = t.GetMethods();
        foreach (MethodInfo method in methods)
        {
            // Invoke a certain method
        }
    }
}

The problem is that I don't know the instance of the class that contains that certain method. So I can't invoke it properly because the methods are not static. I also want to avoid creating a new instance of this class if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...