【问题标题】:passing type of property to generic type将属性类型传递给泛型类型
【发布时间】:2015-05-26 08:42:44
【问题描述】:

我有一个generic class GenericClass<T> 出于某种原因,我需要从其他类型传递泛型类型:

说我有一些classesNormalClass1NormalClassN 他们都有属性说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

【问题讨论】:

标签: c# generics


【解决方案1】:

您的代码存在多个问题。 首先:

var type1 = typeof(NormalClass1).GetProperty("prop1").GetType();

将返回类型PropertyInfo,而不是属性的类型。你想要的是:

var type1 = typeof(NormalClass1).GetProperty("prop1").PropertyType;

其次,您似乎在泛型、类型和类型参数方面存在概念问题。

Type 变量(Type x = typeof(NormalClass1&lt;&gt;)和泛型 Type 参数(NormalClass&lt;T&gt; 中的 T)基本上是有区别的。 T 只不过是类型的占位符。您可以使用typeof(T) 获取T 的实际类型。另一方面,使用 typeof(x) 会导致计算错误,因为 x 是变量而不是类型。你可以改用x.GetType()

您不能直接通过运行时类型变量创建泛型类型。 您可以做的是通过反射创建泛型类型。

下面的例子应该说明如何做到这一点

var genericTypeParameter = typeof(NormalClass1).GetProperty("prop1").PropertyType;
var genericBaseType = typeof(GenericClass<>);
var genericType = genericBaseType.MakeGenericType(genericTypeParameter);
var instance = Activator.CreateInstance(genericType);

如您所见,var instance 将替换为 object instance。必须这样,因为您可以检查编译时间的类型。最佳实践可能是为您的泛型类创建一个非泛型基类。您可以使用基类类型并在运行时至少进行少量类型检查,即使您没有机会测试泛型类型参数。

这将是它的样子:

var instance = (GenericClassBase)Activator.CreateInstance(genericType);

【讨论】:

    【解决方案2】:

    你只能用反射来做到这一点:

        var generic = typeof (GenericClass<T>).MakeGenericType(type1);
        var instance = Activator.CreateInstance(generic);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多