Construct a System.Type for a generic interface with known type of T [duplicate]

做~自己de王妃 提交于 2019-12-24 20:56:40

问题


PROBLEM DESCRIPTION

I have an interface definition IFoo<TBar> : IFoo and a method CreateFooUsingBarType(Type barType). I need the method to resolve an IFoo<TBar> using a dependency injection tool given a specified System.Type instance that defines TBar. Don't ask how I ended up here. I am stuck within these boundaries.

EXAMPLE

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);
}

I've tried mucking around with TypeBuilder but I'm getting the sense that it's overkill for this. Does .NET expose a different API for achieving this?

Thanks in advance.


回答1:


You can use the MakeGenericType method:

var fooType = typeof(IFoo<>).MakeGenericType(barType);


来源:https://stackoverflow.com/questions/49467951/construct-a-system-type-for-a-generic-interface-with-known-type-of-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!