Use C # reflection to access an object using stacktrace

I would like to use reflection in .NET to access the object that called my method. I guess you can somehow view the stack. I know this is not safe for various reasons, but I just need to capture and catalog some property values.

How to do it?

Update : I'm an idiot, I forgot to say that it was in C #

+3
source share
3 answers
var methodInfo = new StackFrame(1).GetMethod();

Returns a method that calls the current method.

, ( , ), . , :

[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]

, . emptor.

EDITED. , , . .

+5

, ?

( ) , ?

+2

StackTrace StackFrame

MSDN

http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.aspx

, "Main"

class Program
{
    static void Main(string[] args){
        Func();
    }
    static void Func(){
        StackFrame frame = new StackFrame(1);
        StackTrace trace = new StackTrace(frame);
        var method = frame.GetMethod();
        Console.WriteLine(method.Name);
    }
}
+2

Source: https://habr.com/ru/post/1714580/


All Articles