I would recommend trying to solve this by having the
Class1
and
Class2
implement some sort of
ISaveable
interface instead, but if that can't be done then here's two different solutions.
The first one tries to find any matching extension method in the calling assembly, and the second one is slightly more efficient but forces you to specify the type owning the extension methods:
public static class Extensions
{
public static void Save(this A instance)
{
Console.WriteLine("Saving A");
}
public static void Save(this B instance)
{
Console.WriteLine("Saving B");
}
private static bool IsMethodOk(MethodInfo method, object obj)
{
return
method.IsStatic
&&
method.GetParameters().Count() == 1
&&
method.GetParameters()[0].ParameterType == obj.GetType();
}
public static void Save1(this IList<object> list)
{
foreach (object obj in list)
{
foreach (Type type in Assembly.GetCallingAssembly().GetTypes())
{
bool hasSaved = false;
foreach (MethodInfo method in type.GetMethods())
{
if (IsMethodOk(method, obj))
{
method.Invoke(null, new[] { obj });
hasSaved = true;
break;
}
}
if (hasSaved)
break;
}
}
}
public static void Save2(this IList<object> list, Type extensionClass)
{
foreach (object obj in list)
{
foreach (MethodInfo method in extensionClass.GetMethods())
{
if (IsMethodOk(method, obj))
{
method.Invoke(null, new[] { obj });
break;
}
}
}
}
}
Hope this helps,
Fredrik