Home > Backend Development > C++ > How to Invoke Static Methods Using Reflection in C#?

How to Invoke Static Methods Using Reflection in C#?

Mary-Kate Olsen
Release: 2024-12-28 18:45:13
Original
880 people have browsed it

How to Invoke Static Methods Using Reflection in C#?

Invoking Static Methods with Reflection

Problem:

You possess several static classes within the namespace mySolution.Macros, each containing static methods like:

public static class Indent
{
    public static void Run()
    {
        // implementation
    }
}
Copy after login

Your objective is to invoke these methods using reflection, even though they are static.

Solution:

To invoke static methods with reflection while preserving their static nature, employ the following approach:

foreach (var tempClass in macroClasses)
{
    // Note that the first argument is ignored for static methods
    tempClass.GetMethod("Run").Invoke(null, null);
}
Copy after login

As mentioned in the documentation for MethodInfo.Invoke, the first argument is redundant for static methods, so you can safely pass null.

Binding Flags:

It is important to note that you may need to specify binding flags when invoking the method, as suggested in the comment:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);
Copy after login

This ensures that the method is public and static, which is necessary for proper invocation.

The above is the detailed content of How to Invoke Static Methods Using Reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template