Instantiate object with reflection and dynamic arg

2019-08-07 09:10发布

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.

标签: c# reflection
1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-07 09:59

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); 
}
查看更多
登录 后发表回答