Reputation: 2094
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();
When A
constructor is called, variable props
contains only PropA
. It's possible to get all properties (PropA
and PropB
)?
Upvotes: 0
Views: 732
Reputation: 19305
A base class is not supposed to know anything about its derived classes. It breaks the Open Closed Principle and the Liskov Substitution Principle.
You solve this using generics and virtual or abstract methods. Also, don't be writing your own O/R Mapper. There are so many out there, that some must cover your needs!
Upvotes: 0
Reputation: 2709
You could do:
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();
Upvotes: 0
Reputation: 34407
This one works for me:
var props = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
Upvotes: 2
Reputation: 12458
The constructor of base class A
is run before the constructor of the derived class B
, so you can not access the properties of the derived class.
BTW: This doens't make sense to me, that a base class has knowledge of the derived classes!
Upvotes: 0
Reputation: 26737
The Parent class(where you have defined the constructor) does not know anything about its child class that's why it returns just PropA
If you define the constractor in the B
class it will return both the properies
Upvotes: 0