是否可以确定实例化类的当前实例的类的哪个实例?

CJC*_*CJC 4 c#

正如标题所示,可以确定实例化另一个类的特定实例的类的哪个实例?

更新:示例代码如下

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;
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*man 7

是的,您可以像常规方法一样为构造函数执行此操作.只需使用CallerMemberName传递调用方法的名称即可.你不会拥有它的类名,那么你需要走StackTrace更复杂的东西.

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

    public string Caller { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)

然后打电话给这个.编译器会caller为您填写参数:

static void Main(string[] args)
{
    X x = new X();
    Console.WriteLine($"Caller = {x.Caller}"); // prints Main
}
Run Code Online (Sandbox Code Playgroud)