MethodInfoClass mic = new MethodInfoClass(); const BindingFlags bindingFlags = BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; System.Reflection.MethodInfo privateTestMethod = typeof(MethodInfoClass).GetMethod("PrivateTestMethod", bindingFlags); if (privateTestMethod is not null) { string returnFromPrivateTestMethod = (string)privateTestMethod.Invoke(mic, null); Console.WriteLine($"privateTestMethod: {returnFromPrivateTestMethod}"); }Example project download from here.
Invoke private method with reflection
- Details
- Written by: Stanko Milosev
- Category: C#
- Hits: 1646
I have added a class library, and introduced one private method. Invoke looks like: