【问题标题】:how to get type from a partially closed generics如何从部分封闭的泛型中获取类型
【发布时间】:2017-04-29 23:55:11
【问题描述】:

-- 已编辑--

但是当我得到一个复杂的泛型时:

class Class<T> : Interface<T, List<T>>
{
    // ...
}

我怎样才能得到typeof(Interface&lt;, List&lt;&gt;&gt;)

//typeof(Interface&lt;, List&lt;&gt;&gt;)有编译错误

我真的不想用typeof(Class&lt;&gt;).GetInterfaces()[0]

有什么想法吗?

【问题讨论】:

  • 这段代码的确切用途是什么,你已经有泛型类型 T,直接使用它
  • @MrinalKamboj 我尝试使用DependencyInjection
  • 您的目的是映射,以便在运行时通过 DI 框架调用正确的具体实现。是否是 DI 绑定问题。

标签: c#


【解决方案1】:

您需要准确地传递所有泛型参数在您的界面中的显示方式。

        int i = 1; // just for example, any suitable type
        var type = i.GetType();
        var listType = typeof(List<>).MakeGenericType(type);
        var intfType = typeof(I1<,>).MakeGenericType(type, listType);

编辑

如果我最终正确理解了 OP - 你不能这样做。类型可以是开放式或封闭式。您可以混合使用其他泛型和非泛型类型来定义泛型类型(类和接口),但也可以专门用于定义类型。您不能在运行时根据这些定义构造部分封闭或部分修改的泛型类型。为了做你想做的事,你需要引入另一个接口,它只定义一个泛型参数,然后用它来操作:

        interface GenericInterface<T1, T2>
        {
        }

        interface ListInterface<T> : GenericInterface<T, List<T>>
        {

        }

        class Class1<T> : ListInterface<T>
        {
            // ...
        }

        var blah = typeof(ListInterface<>); // this is the exact interface that Class1 implements

【讨论】:

  • 当我使用依赖注入时,它需要传递一个泛型类型,以便它可以动态构建封闭类型。
  • @Cologler 对于您编写的代码,他提供了一个正确的示例,是与 DI 绑定相关的问题
  • @MrinalKamboj 但我要求typeof() 提供泛型类型,而不是封闭类型。它用于构建 DI 容器,而不是从 DI 容器中获取实例。
  • @Cologler,我已经完美地回答了您的问题,该问题没有说一句话或包含任何有关使用 DI 的提示。 ;) 你应该正确地问它,说你想要它在 DI 中,因为答案会完全不同。
  • @AlexanderLeonov 你的intfType.ContainsGenericParameters 将返回false,但我所有预期的类型(如typeof(Class&lt;&gt;).GetInterfaces()[0]).ContainsGenericParameters 将返回true。有点不同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-12
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多