简体   繁体   中英

Call generic method and to call method on return type

How would I go about calling a generic method only knowing the type at runtime and also to then call a method on the type returned? I have a looked at a lot of examples but can't seem to get it working.

This is what I have so far.

public interface IDataMapper<TEntity> where TEntity : IEntity
{
    void Update(TEntity entity);
}

public IDataMapper<TEntity> GetMapper<TEntity>() where TEntity : IEntity
{
    // Return something of type IDataMapper<TEntity>
}

foreach (IEntity entity in _dirtyObjects)
{
    MethodInfo method = typeof(MapperFactory).GetMethod("GetMapper");
    MethodInfo generic = method.MakeGenericMethod(entity.GetType());

    generic.Invoke(_mapperFactory, null);
    // I now want to call the Update() method
    // I have tried to cast to IDataMapper<IEntity> which results in a null ref ex
}

Thanks for any advice.

You have to keep working with reflection:

object dataMapper = generic.Invoke(_mapperFactory, null);
method = dataMapper.GetType().GetMethod("Update");
method.Invoke(dataMapper, new object[] {entity});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM