public
Created

Call generic implementation of method using Reflection

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
void Main()
{
GetPersisterFor(new Foo());
}
 
public interface IPersister { }
public interface IEntity { }
public class Foo : IEntity { }
public class Bar : IEntity { }
 
public IPersister GetPersisterFor(IEntity entity)
{
Console.WriteLine("Call GetPersisterFor(IEntity entity)");
MethodInfo getPersisterForGenericMethod =
GetType().GetMethods()
// iterate over all methods to find proper generic implementation
.Single(methodInfo => methodInfo.Name == "GetPersisterFor" && methodInfo.IsGenericMethod)
// supply it with generic type parameter
.MakeGenericMethod(entity.GetType());
 
// invoke it
return getPersisterForGenericMethod.Invoke(this, null) as IPersister;
}
 
public IPersister GetPersisterFor<TEntity>() where TEntity : IEntity
{
Console.WriteLine("Call GetPersisterFor<TEntity>");
return null;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.