Home >Backend Development >C++ >Can C# Reflection Reveal the Calling Method's Name and Type?
Accessing Calling Method Details Through Reflection
Question:
Can reflection in C# be utilized to retrieve the name and type of the method that invoked the current method?
Answer:
Yes, it is possible. Here's a code demonstration on how to achieve this:
public class SomeClass { public void SomeMethod() { StackFrame frame = new StackFrame(1); MethodBase method = frame.GetMethod(); Type type = method.DeclaringType; string name = method.Name; } }
Consider the following additional class:
public class Caller { public void Call() { SomeClass s = new SomeClass(); s.SomeMethod(); } }
In this scenario, the variables name and type will be assigned with the values "Call" and "Caller", respectively.
Update for .NET 4.5:
Introduced in .NET 4.5, the CallerMemberNameAttribute simplifies this process. In the modified SomeClass below:
public class SomeClass { public void SomeMethod([CallerMemberName]string memberName = "") { Console.WriteLine(memberName); // Outputs the calling method's name } }
This replaces the need for the StackFrame and GetMethod() methods.
The above is the detailed content of Can C# Reflection Reveal the Calling Method's Name and Type?. For more information, please follow other related articles on the PHP Chinese website!