class Program { static void Main(string[] args) { //通过反射来调私有的成员 Type type = typeof(Person); //BindingFlags类型枚举,BindingFlags.NonPublic | BindingFlags.Instance 组合才能获取到private私有方法 MethodInfo methodInfo = type.GetMethod("SayHello", BindingFlags.NonPublic | BindingFlags.Instance); object obj = Activator.CreateInstance(type); //通过反射类型创建实例对象 methodInfo.Invoke(obj, null); } } public class Person { private void SayHello() { Console.WriteLine("我是私有方法。"); Console.ReadKey(); } }
时间: 2024-11-05 18:51:53