...see more

You can use the following code snippets to get a class's public methods using reflection. The class name is provided as typeName.

MethodInfo[] methodInfos = typeof(Class).GetMethods();

Variant with filter using BindingFlags

MethodInfo[] methodInfos = Type.GetType(typeName) 
                           .GetMethods(BindingFlags.Public | BindingFlags.Instance);
...see more

You can use this code to get only the methods decorated with a custom attribute.

MethodInfo[] methodInfos = assembly.GetTypes()
                      .SelectMany(t => t.GetMethods())
                      .Where(m => m.GetCustomAttributes(typeof(CustomAttribute), false).Length > 0)
                      .ToArray();
...see more

Here’s an example of how to invoke a private method using reflection in .NET:

MyClass myClass = new MyClass();
Type classType = myClass.GetType();
MethodInfo methodInfo = classType.GetMethod("MethodName",
                BindingFlags.Instance | BindingFlags.NonPublic);
 
// Make an invocation:
var result = await (dynamic)methodInfo.Invoke(myClass, null);
...see more

You can get private property like so:

Class class = new Class();
var privateProperty = class.GetType().GetProperty("privateProperty", BindingFlags.Instance | BindingFlags.NonPublic);
int propertyValue = (int) privateProperty.GetValue(class);

var privateField = class.GetType().GetField("privateField", BindingFlags.Instance | BindingFlags.NonPublic);
int fieldValue = (int) privateField.GetValue(class);

Comments

Leave a Comment

All fields are required. Your email address will not be published.