I think I found a solution using Reflection. Let me explain:
1- You extract all types derived from your BaseRecord.
2- You extract all your processing methods (they take 1 argument, and this argument inherits from BaseRecords)
3- Since you have only 1 processing function per type, you make a dictionary (the key will be the type, and the value is the corresponding processing method)
4- the 'magical' function you are looking for is just getting the method out of the dictionary according to the input type.
I tried the code below and it seems to work. But even if this works, it is not very elegant. I mean, the most natural way to do the job here is to use virtual methods as everyone advises. And I would recommand that you use their suggestion.
Anyway, here is the code:
class Base { }
class DerivedClass1 : Base { }
class DerivedClass2 : Base { }
class Process
{
public Process()
{
Type baseType = typeof(Base);
Assembly thisAssembly = Assembly.GetAssembly(baseType);
Type[] allTypes = thisAssembly.GetTypes();
IEnumerable<Type> baseTypes =
from type in allTypes
where type.IsSubclassOf(baseType)
select type;
MethodInfo[] methods = typeof(Process).GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
List<MethodInfo> processingMethods = new List<MethodInfo>();
foreach (MethodInfo method in methods)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType.IsSubclassOf(baseType))
processingMethods.Add(method);
}
Dictionary<Type, MethodInfo> dictionary = new Dictionary<Type, MethodInfo>();
foreach (Type type in baseTypes)
{
foreach (MethodInfo method in processingMethods)
if (method.GetParameters()[0].ParameterType.Equals(type))
dictionary[type] = method;
}
Base[] baseRecords = new Base[]
{
new DerivedClass1(),
new DerivedClass2(),
new DerivedClass1()
};
foreach (Base baseRec in baseRecords)
dictionary[baseRec.GetType()].Invoke(this, new object[] { baseRec });
}
void ProcessDerivedClass1(DerivedClass1 param)
{
System.Diagnostics.Debug.Print("Processing object1...");
}
void ProcessDerivedClass2(DerivedClass2 param)
{
System.Diagnostics.Debug.Print("Processing object2...");
}
}
class Program
{
static void Main(string[] args)
{
new Process();
}
}