How to determine who is the creator of an object

I have a class that is regularly called multiple objects. I would like to include information in any exceptions who is the creator of the object. What are my options?

“Who” refers to an object or class

+3
source share
10 answers

Keep stack when constructor is called. This is similar to what SlimDX does in debug builds.

+4
source

Maybe I missed something, but I'm sure the only way to do this is to manually pass this information, fe. in the constructor of your object.
Edit: If this is what you were looking for?


class Creator
{
    public string Name { get; private set; }

    public Creator(string name)
    {
        Name = name;
    }
}

class Foo
{
    readonly Creator creator;
    public Foo(Creator creator)
    {
        this.creator = creator;
    }

    public void DoSth()
    {
        throw new Exception("Unhandled exception. My creator is " + creator.Name);
    }
}

public static void Main()
{
    Foo f = new Foo(new Creator("c1"));
    f.DoSth();
}
+2
source

, Environment.StackTrace . .

+2

"" :

MyObject myObj = new MyObject(this);

.

+1

. StackTrace.GetFrames. , . , . , , .

, . , , / .

+1

; , . , , ?

, , - , ():

factory . , ; factory.

, , factory + . , . , #ifdefs.

+1

StackTrace / GetFrame. , , , ( , Factory).

, - .

using System.Diagnostics;
// get call stack
StackTrace stackTrace = new StackTrace();

// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

, " " , , .

0

- , :

public class Foo
{

    private Type ParentAtCreation = null;

    public Foo()
    {
        ParentAtCreation = (new StackTrace())
            .GetFrame(1)
            .GetMethod()
            .DeclaringType;
    }
}
0

,

, , winforms , , ,

,

, , , ,

Admin_Login ad = new Admin_Login(Enrol, this);
                ad.Show();
                this.Visible = false;

, , .

Admin_Login

public Admin_Login(string Enrol,Form parent)
    {
        Enrollment = Enrol;
        Parent = parent;
        InitializeComponent();
    }

Parent -

B.O.L

0

I am surprised that no one has said this yet, even as a warning for their own decision, so I will: this is generally a bad idea, and if you need to do this, it is usually a huge indicator that something is wrong with your design . If you go down this route to solve your problem, you will end up causing much bigger problems in the future. It is best to take 2 steps back and fix the design that makes this necessary.

0
source

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


All Articles