CSharp · Console
using System;
using System.Linq;
using System.Reflection;
namespace test
{
static class PRD
{
public static dynamic prdData { get; private set; } = new PRD_P20();
}
public abstract class PRD_DATA
{
public BLE ble = new BLE();
public class BLE : PRD_BLE_BASE { }
}
public abstract class PRD_BLE_BASE
{
public PSR psr = new PSR();
}
public class PSR
{
public string timestamp = "original";
}
public class PRD_P20 : PRD_DATA
{
/* Instantiate new version BLE and hide the parent class */
public new BLE ble = new BLE();
public new class BLE
{
public PSR psr = new PSR();
}
public class PSR
{
public string timeStamp = "updated";
}
}
class Program
{
static void Main(string[] args)
{
dynamic prdData = PRD.prdData;
TypeInfo prdDataType = prdData.GetType();
var filteredFields = prdDataType.GetFields().Where( x => x.DeclaringType == prdDataType).ToList();
foreach (FieldInfo prdDataField in filteredFields)
{
object prdFieldValue = prdDataField.GetValue(prdData);
Console.WriteLine("Found field '{0}' declared in type '{1}' with a value of '{2}' which is of type '{3}'", prdDataField.Name, prdDataField.DeclaringType, prdFieldValue, prdFieldValue.GetType().FullName);
foreach (FieldInfo f1 in prdFieldValue.GetType().GetFields())
{
object o2 = f1.GetValue(prdFieldValue);
foreach (FieldInfo f2 in o2.GetType().GetFields())
{
Console.WriteLine("f2.Name:" + f2.Name + ": " + f2.GetValue(o2));
}
}
}
try
{
Console.WriteLine(PRD.prdData.ble.psr.timestamp); // Fails RuntimeBinderException
throw new Exception("This shouldn't happen");
}
catch(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException exception)
{
Console.WriteLine("Could not find timestamp with a lowercase s, as expected.");
}
Console.WriteLine(PRD.prdData.ble.psr.timeStamp);
}
}}