2

我将如何在运行时只知道类型的情况下调用泛型方法,然后在返回的类型上调用方法?我查看了很多示例,但似乎无法使其正常工作。

这就是我到目前为止所拥有的。

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
}

感谢您的任何建议。

4

1 回答 1

4

您必须继续使用反射:

object dataMapper = generic.Invoke(_mapperFactory, null);
method = dataMapper.GetType().GetMethod("Update");
method.Invoke(dataMapper, new object[] {entity});
于 2012-09-27T23:23:42.113 回答