我们假设我们有以下课程:
class BaseClass
{
public BaseClass()
{
//sth to do
HERE I WOULD LIKE TO KNOW WHICH CHILD CLASS INVOKES BASE CONSTRUCTOR
}
}
class ChildClass : BaseClass
{
public ChildClass() : base() {}
}
如上所述,我想在运行时找出哪个子类调用了基类构造函数?
答案 0 :(得分:1)
对象的实际类型
public BaseClass()
{
Type actualType = this.GetType();
if(actualType == typeof(ChildClass))
{
// we are the child class
}
else
{
// we are not...
}
}
调用此构造函数的构造函数
这有点困难,但如果仅用于调试目的,您可以检查调用方法:
public BaseClass()
{
StackTrace stackTrace = new StackTrace();
MethodBase callingMethod = stackTrace.GetFrame(1).GetMethod();
Type callingType = callingMethod.DeclaringType;
// Then as above, check the type as required
}
答案 1 :(得分:0)
有可能但是要知道它非常讨厌,我会在生产代码中重新考虑使用它:
class BaseClass
{
public BaseClass()
{
StackTrace st = new StackTrace();
string child = st.GetFrame(1).GetMethod().DeclaringType.Name;
// ...
}
}