I have a simple program that uses reflection to print out the properties and values of the supplied class.
class BaseClass
{
public string A
{
get { return "BaseClass"; }
}
}
class Child1 : BaseClass
{
public string Child1Name {
get { return "Child1"; }
}
}
class Child2 : BaseClass
{
public string Child2Name
{
get { return "Child2"; }
}
}
class Program
{
static void Main(string[] args)
{
var child1 = new Child1();
var child2 = new Child2();
SomeMethod(child1);
SomeMethod(child2);
Console.ReadKey();
}
static void SomeMethod(BaseClass baseClass)
{
PrintProperties(baseClass);
}
static void PrintProperties<T>(T entity)
{
var type = typeof(T);
foreach (var targetPropInfo in type.GetProperties())
{
var value = type.GetProperty(targetPropInfo.Name).GetValue(entity);
Console.WriteLine("{0}: {1}", targetPropInfo.Name, value);
}
Console.WriteLine("");
}
}
The problem is that it only prints out the BaseClass
properties because I am using generics and passing in the BaseClass
into the PrintProperties
method.
Output:
A: BaseClass
A: BaseClass
How do I access the properties of the Child classes? I would like an output like:
A: BaseClass
Child1Name: Child1A: BaseClass
Child2Name: Child2
The problem here is that you're using typeof(T)
in PrintProperties
, but the T
in your example is BaseClass
because that's the type of the parameter you give it from SomeMethod
.
In your example, remove SomeMethod
, call the PrintProperties
method directly and it'll work.
A simpler way would be to use entity.GetType()
instead of typeof(T)
. That way, no matter what the generic type is, you'll always get the true type of the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With