Is it possible to determine from which class instance the current class instance is instantiated?

As the name implies, you can determine from which instance of the class an instance of another instance of another class is created?

Update: Sample code below

class FooBar: Foo
{
    private Context context;
    public FooBar(Context _context): base(_context)
    {
        this.context = _context;
    }
}

class Foo
{
    public Baz baz;
    private Context context; 
    public Foo(Context _context)
    {
        baz = new Baz();
        this.context = _context;
    }
}

class Baz
{
    public Baz()
    {
        GetNameOfCaller()
    }

    private void GetNameOfCaller()
    {
       ....
       ....
       _className = ....;
    }
    private string _className;
}
+4
source share
3 answers

You can use System.Diagnostics.StackTrace:

public class Foo 
{
    public void MethodBah()
    {
        System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
        MethodBase callingMethod = t.GetFrame(1).GetMethod();
        Type callingMethodType = callingMethod.DeclaringType;
        string className = callingMethodType.Name;
    }
}

Works even in .NET 1.1.


With your (updated) example, you need to use t.GetFrame(2).GetMethod()instead GetFrame(1)to get FooBarinstead Foo, because the child call invokes the parent constructor.

+4
source

, , . CallerMemberName . , StackTrace, .

public class X
{
    public X([CallerMemberName] string caller = null)
    {
        this.Caller = caller;
    }

    public string Caller { get; private set; }
}

. caller :

static void Main(string[] args)
{
    X x = new X();
    Console.WriteLine($"Caller = {x.Caller}"); // prints Main
}
+7

, - .

OP :

[..] , [...]

, PostSharp, , , :

[Serializable]
public class LogAspect : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
    }

    public override void OnExit(MethodExecutionArgs args)
    {
    }
}

, ( , ).

MethodExecutionArgs.Method ( MethodBase, , MethodBase.DeclaringType.

, PostSharp, , , . , .

, - , Castle DynamicProxy .

+2

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


All Articles