【问题标题】:Which class invokes base constructor哪个类调用基构造函数
【发布时间】:2013-11-29 15:13:11
【问题描述】:

假设我们有以下类:

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() {}
}

如上所述,我想在运行时找出哪个子类调用了基类构造函数?

【问题讨论】:

  • 应该public BaseClass()public ChildClass()
  • 给定class Baseclass Derived1 : Baseclass Derived2 : Derived1,将是Derived1的构造函数调用Base的构造函数,但对象的类型为Derived2。你想看前者还是后者?
  • 老实说,这听起来像是个坏主意(TM)。基类不必知道其继承者的任何信息即可正常运行。您要解决的具体问题是什么?
  • this.GetType() 就够了吗? (注意:在多级层次结构中,这将始终给出具体类型,而不是直接子类型)
  • 我同意@lc。这是一个 XY 问题。你想做什么?

标签: c# constructor base


【解决方案1】:

@hvd 在 cmets 中指出,您可能需要两种可能的行为。

对象的实际类型

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
}

【讨论】:

    【解决方案2】:

    这是可能的,但请注意这很讨厌,我会重新考虑在生产代码中使用它:

    class BaseClass
    {
        public BaseClass()
        {
            StackTrace st = new StackTrace();
            string child = st.GetFrame(1).GetMethod().DeclaringType.Name;
            // ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-19
      • 2011-02-12
      • 2018-07-21
      • 2017-04-13
      • 2013-03-24
      • 2015-08-18
      • 2018-07-16
      • 2011-05-22
      • 2018-03-31
      相关资源
      最近更新 更多