繁体   English   中英

在父构造函数中获取子类属性

[英]Get child class properties in parent constructor

class A
{
    public string PropA {set; get;}

    public A()
    {
        var props = this.GetType().GetProperties(BindingFlags.Public);
    }
}


class B : A
{
    public string PropB {set; get;}
}

var b = new B();

A构造函数,变量props只包含PropA 可以获得所有属性( PropAPropB )?

这个对我有用:

var props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

Parent类(您已经定义了构造函数)对它的子类没有任何了解,这就是它返回PropA的原因如果在B类中定义PropA ,它将返回两个属性

基类A的构造函数在派生类B的构造函数之前运行,因此您无法访问派生类的属性。

BTW:这对我来说没有意义,基类知道派生类!

你可以这样做:

class A
{
    public string PropA {set; get;}

    public A()
    {
    }

    protected virtual PropertyInfo[] GetProperties()
    {
        return this.GetType().GetProperties(BindingFlags.Public);
    } 
}


class B : A
{
    public string PropB {set; get;}

    public B() : base()
    {
    }

    public new PropertyInfo[] GetProperties()
    {
        return this.GetType().GetProperties(BindingFlags.Public);
    }
}

var b = new B();
var prop = b.GetPropeties();

基类不应该知道它的派生类。 它打破了开放封闭原则和利斯科夫替代原则。

您可以使用泛型和虚拟或抽象方法来解决此问题。 另外,不要编写自己的O / R Mapper。 那里有很多,有些必须满足你的需求!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM