In C#, private static methods are not directly accessible from outside the class. However, it is possible to invoke a private static method on an instance of a class using Reflection.
Here's an example of how to call a private static method on an instance of a class using Reflection:
main.cs429 chars22 lines
In this example, we use the GetMethod
method from the System.Reflection
namespace to retrieve the MyPrivateStaticMethod
method of the MyClass
class. Since MyPrivateStaticMethod
is private and static, we must specify BindingFlags.NonPublic | BindingFlags.Static
to access it.
The Invoke
method is then used to call the private static method on an instance of the MyClass
class. We pass null
for the instance parameter, since the method is static and does not require an instance.
Note that calling private static methods in this way is generally discouraged, as it can break encapsulation and lead to unexpected behavior. It should only be used as a last resort.
gistlibby LogSnag