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?
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.
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.
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.
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;
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With