代码之家  ›  专栏  ›  技术社区  ›  Sparr

在子类方法中实例化父类

  •  0
  • Sparr  · 技术社区  · 7 年前
    public class Parent {}
    
    public class Child: Parent {
        public Child() {
            Parent instance_of_Parent = INSERTCODEHERE;
        }
    }
    

    2 回复  |  直到 7 年前
        1
  •  2
  •   Sparr    7 年前

    如果您不关心性能,这将起作用:

    public class Child: Parent {
        public Child()
        {
            var baseClass = GetType().BaseType;
            dynamic instance_of_Parent = Activator.CreateInstance(baseClass);
        }
    }
    
        2
  •  0
  •   Sparr    7 年前
    GetType().BaseType.GetConstructor(new Type[]{}).Invoke(null);