如何创建泛型类接受多种类型 C#



我有两个类:

LinkedEntityProvider<TObj, TRes> and HistValidator<TObj>.

在第二个中,您需要创建第一个实例。

PropertyInfo[] props = typeof(TObj).GetProperties();
foreach (PropertyInfo prop in props)
{
var sourceAttrs = prop.GetCustomAttribute<Reference>();
if (sourceAttrs != null)
{
Type entityType = sourceAttrs.ReferenceType;
//Here i need to create LinkedEntityProvider<TObj, TRes> and use type entityType like TRes
}
}

若要构造封闭泛型类型,可以执行以下操作:

var openGenericType = typeof(LinkedEntityProvider<,>);
var closedGenericType = openGenericType.MakeGenericType(typeof(TObj), entityType);
var instance = Activator.CreateInstance(closedGenericType);

第一行获取开放类型,即没有泛型参数。然后,我们将参数提供给MakeGenericType以生成类似于typeof(LinkedEntityProvider<TObj, TRes>)的东西。

有了这个,我们就可以使用创建一个实例Activator.CreateInstance.如果对象构造函数采用任何参数,则必须将它们传递给Activator.CreateInstance,例如:

var instance = Activator.CreateInstance(closedGenericType, new object[] { constructorParameter1, constructorParameter2 });

请注意,由于无法知道在编译时生成的类型,因此Activator.CreateInstance返回object

最新更新