为已知类型为T

时间:2018-03-24 17:53:12

标签: c# reflection inversion-of-control

问题说明

我有一个界面定义IFoo<TBar> : IFoo和一个方法CreateFooUsingBarType(Type barType)。在定义IFoo<TBar>的指定System.Type 实例的情况下,我需要使用依赖注入工具解析TBar的方法。不要问我最后是怎么来的。我被困在这些界限内。

示例

public IFoo CreateFooUsingBarType(Type barType)
{
    var iocScope = GetScope();

    // TODO: Create a System.Type for IFoo<TBar>
    // where TBar is barType. Blarghity blargh.
    var fooType =  (Type)null;

    return iocScope.Resolve(fooType);
}

我已经尝试过使用TypeBuilder,但我觉得这样做太过分了。 .NET是否为实现此目的而公开了不同的API?

提前致谢。

1 个答案:

答案 0 :(得分:3)

您可以使用MakeGenericType方法:

var fooType = typeof(IFoo<>).MakeGenericType(barType);
相关问题