Answers for "Reflection: How to Use MethodInfo"

C#
0

Reflection: How to Use MethodInfo

//MethodInfo
  
//The MethodInfo class discovers the attributes of a method and provides access to method metadata.
//The GetMethods method on the Type class returns all the public instance methods on a type by default. Here, we get an array of MethodInfo instances of all the public MyClass class methods.

System.Reflection.MethodInfo[] methodInfos = myClassType.GetMethods();
//or
System.Reflection.MethodInfo[] methodInfos = myClassType.GetTypeInfo().DeclaredMethods;

//Aslo we can get single MethodInfo by method name
Type type = typeof(MyClass);

MethodInfo info = type.GetMethod("SomeMethod");

//An instance method can be called by its name. With the MethodInfo type, we call the Invoke method. We must provide an instance expression.
var type = typeof(MyClass);

var instance  = new MyClass();

var methodInfo = type.GetMethod("SomeMethod");
    
methodInfo.Invoke(instance, null); // second parameter is array of parameters of the invoked method
Posted by: Guest on August-26-2021

Code answers related to "Reflection: How to Use MethodInfo"

C# Answers by Framework

Browse Popular Code Answers by Language