我怎么知道谁叫thw构造函数 [英] How can i know who call thw constructor

查看:97
本文介绍了我怎么知道谁叫thw构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我想知道调用构造函数的类名称,
我尝试使用堆栈跟踪,但是没有用.这是示例:

Hey, i want to know the class name that call the constructor,
i try with stack trace but didn''t work. here is example:

public class ClassA
{
  public ClassB B {get; privet set;}
  
  public ClassA()
  {
    B = new CLassB();
  }
}

public class ClassB
{
  public ClassB()
  {
     //Here i want to print the class name that call to this consructor (ClassA)
  }
}




10x !!




10x!!

推荐答案

问题与反射无关.使用类System.Diagnostics.StackTraceSystem.Diagnostics.StackFrame解决了此问题.
请参阅:
http://msdn.microsoft.com/en-us/library/system.diagnostics. stacktrace.aspx [ ^ ],
http://msdn.microsoft.com/en-us/library/system. diagnostics.stackframe.getmethod.aspx [ ^ ].

假设您找到了合适的堆栈框架.使用StackFrame.GetMethod获取类型为System.Reflection.MethodBase的调用方法的实例.请参阅:
http://msdn.microsoft.com/en-us/library/system.reflection. methodbase.aspx [ ^ ].

(是的,这部分是反射…:-))

您可以使用属性System.Reflection.MethodBase.DeclaringType找到呼叫者的类型.请参阅:
http://msdn.microsoft.com/en-us/library/system. Reflection.memberinfo.declaringtype.aspx [ ^ ].

一切都非常简单;很难说你会在哪里迷路.只需阅读MSDN帮助页面即可.

—SA
The question has little to do with Reflection. This problem is solved using the classes System.Diagnostics.StackTrace and System.Diagnostics.StackFrame.

Please see:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx[^],
http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx[^].

Let''s assume you found appropriate stack frame. Use StackFrame.GetMethod to get an instance of the calling method of the type System.Reflection.MethodBase. Please see:
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.aspx[^].

(And yes, this part is Reflection… :-))

You will find the type of the caller using the property System.Reflection.MethodBase.DeclaringType. Please see:
http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.declaringtype.aspx[^].

Everything is pretty simple; it''s hard to say where could you have lost. Just read MSDN help pages.

—SA


您确实需要使用StackFrame,但是需要访问MethodBase类的DeclaringType:

You do need to use the StackFrame, but you need to access the DeclaringType of the MethodBase class:

StackTrace st = new StackTrace(true);
foreach ( StackFrame sf in st.GetFrames())
    {
    Console.WriteLine(sf.GetMethod().DeclaringType);
    }


这篇关于我怎么知道谁叫thw构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆