public class MyClass { private int myField = 10; } MyClass obj = new MyClass(); FieldInfo field = typeof(MyClass).GetField("myField", BindingFlags.NonPublic | BindingFlags.Instance); int fieldValue = (int)field.GetValue(obj); Console.WriteLine(fieldValue); // Output: 10
public class MyClass { public int MyMethod(int a, int b) { return a + b; } } MyClass obj = new MyClass(); MethodInfo method = typeof(MyClass).GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Instance); int result = (int)method.Invoke(obj, new object[] { 1, 2 }); Console.WriteLine(result); // Output: 3In this example, we invoke a method of the `MyClass` class using BindingFlags.InvokeMethod. First, we create an object of the `MyClass` class and then get the `MethodInfo` object for the `MyMethod` method using the `GetMethod` method of the `Type` class. We pass the `BindingFlags.Public` and `BindingFlags.Instance` flags to indicate that we want to access a public instance method. Finally, we invoke the method using the `Invoke` method of the `MethodInfo` class and pass the object on which to invoke the method and the arguments to the method in an array. Package library: The `System.Reflection` namespace in the .NET Framework contains the `BindingFlags` enum and other related classes and interfaces that developers can use to work with reflection in .NET.