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
Mary-Kate OlsenOriginal
2024-12-28 18:45:13883browse

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

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

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

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!

Statement:
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