Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using System.Reflection to Get a Method's Full Name

I have a class that look like the following:

public class MyClass {  ...      protected void MyMethod()     {     ...     string myName = System.Reflection.MethodBase.GetCurrentMethod.Name;     ...     }  ...  } 

The value of myName is "MyMethod".

Is there a way that I can use Reflection to get a value of "MyClass.MyMethod" for myName instead?

like image 870
Onion-Knight Avatar asked Jun 03 '10 17:06

Onion-Knight


People also ask

How to get all method name in C#?

To get the list of methods in class you normally use the GetMethods method. This method will return an array of MethodInfo objects. We have a lot of information about a method in the MethodInfo object and the name is one of them. BindingFlags and MethodInfo enumerations are part of System.

What is System reflection used for?

Reflection Namespace. Contains types that retrieve information about assemblies, modules, members, parameters, and other entities in managed code by examining their metadata. These types also can be used to manipulate instances of loaded types, for example to hook up events or to invoke methods.

What is System reflection?

The System. Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values, and objects to the application.


2 Answers

You could look at the ReflectedType of the MethodBase you get from GetCurrentMethod, i.e.,

MethodBase method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = method.Name; string className = method.ReflectedType.Name;  string fullMethodName = className + "." + methodName; 
like image 182
Ruben Avatar answered Sep 23 '22 23:09

Ruben


And to get the full method name with parameters:

var method = System.Reflection.MethodBase.GetCurrentMethod(); var fullName = string.Format("{0}.{1}({2})", method.ReflectedType.FullName, method.Name, string.Join(",", method.GetParameters().Select(o => string.Format("{0} {1}", o.ParameterType, o.Name)).ToArray())); 
like image 31
mms Avatar answered Sep 22 '22 23:09

mms