Created
December 26, 2012 10:50
-
-
Save akimboyko/4379572 to your computer and use it in GitHub Desktop.
Call generic implementation of method using Reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment