【发布时间】:2015-05-26 08:42:44
【问题描述】:
我有一个generic class GenericClass<T>
出于某种原因,我需要从其他类型传递泛型类型:
说我有一些classes 从NormalClass1 到NormalClassN 他们都有属性说prop1 和不同的types
我需要这样做
var type1 = typeof(NormalClass1).GetProperty("prop1").GetType();
然后像这样将type1 发送到GenericClass 的新实例:
var instance = new GenericClass<type1>();
但是发生了一个错误提示
Cannot implicitly convert type 'GenericClass<type1>' to 'GenericClass<T>'
如何将此类型传递给GenericClass
【问题讨论】:
-
你试过先转换成T吗?如果
NormalClass1.prop1是类型或继承自T,则只需将其显式转换为T。如果它不是从T继承的,那么你显然不能这样做。 -
您只知道运行时的泛型类型,因此您需要运行时特性来创建泛型类型。你不能这样使用 new 。类似
typeof(GenericClass<>).MakeGenericType(type1)