为具有已知T类型的通用接口构造一个System.Type [英] Construct a System.Type for a generic interface with known type of T

查看:113
本文介绍了为具有已知T类型的通用接口构造一个System.Type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题描述

我有一个接口定义IFoo<TBar> : IFoo和一个方法CreateFooUsingBarType(Type barType).我需要使用给定定义了TBar的指定System.Type instance 的依赖项注入工具来解析IFoo<TBar>的方法.不要问我怎么到这里来了.我陷入了这些界限.

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.

示例

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?

谢谢.

推荐答案

您可以使用 MakeGenericType 方法:

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

这篇关于为具有已知T类型的通用接口构造一个System.Type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆