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
Aucun commentaire:
Enregistrer un commentaire