简体   繁体   English

使用反射和动态参数计数实例化对象

[英]Instantiate object with reflection and dynamic arguments count

I have some class. 我上课。 And by reflection i get it constructor and parameters count/type. 通过反思,我得到它的构造函数和参数计数/类型。 also i have builder for any type. 我也有任何类型的建设者。 so i need to make 所以我需要做

var constructor;
var params = constructor.GetParameters();
object[] args;
foreach( var param in params ) {
    var type = param.Parametertype;
    args[] += (object)Build<type>();
}

Activator.CreateInstance(Type, args);

The problem, that i can not pass the type of parameter as generic argument. 问题是,我无法将参数类型作为通用参数传递。

No, you'll need to use reflection to call the generic method too: 不,您还需要使用反射来调用泛型方法:

var constructor = ...;
var parameters = constructor.GetParameters();
object[] args = new object[parameters.Length];
// Adjust this for private methods etc
var buildMethod = typeof(ClassContainingBuild).GetMethod("Build");
for (int i = 0; i < args.Length; i++)
{
    var genericBuild = buildMethod.MakeGenericMethod(parameters[i].ParameterType);
    // Adjust appropropriately for target etc
    args[i] = genericBuild.Invoke(this, null); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM