反射以ConstructorInfo调用构造函数 [英] Reflection to invoke the constructor with ConstructorInfo
本文介绍了反射以ConstructorInfo调用构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在如下所示的非常简单的课程中,
In a very Simple class like below,
class Program
{
public Program(int a, int b, int c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
我使用反射来调用构造函数
and I use reflection to invoke the constructor
类似这样的东西...
something like this...
var constructorInfo = typeof(Program).GetConstructor(new[] { typeof(int), typeof(int), typeof(int) });
object[] lobject = new object[] { };
int one = 1;
int two = 2;
int three = 3;
lobject[0] = one;
lobject[1] = two;
lobject[2] = three;
if (constructorInfo != null)
{
constructorInfo.Invoke(constructorInfo, lobject.ToArray);
}
但是我收到一条错误消息,说对象与目标类型的构造函数信息不匹配。
But I am getting an error saying "object does not match target type constructor info".
任何帮助/评论都非常感谢。
预先表示感谢。
any help/comments greatly appreciated. thanks in advance.
推荐答案
您不需要传递 constructorInfo
作为参数,在您调用构造函数时,而不是在调用对象的实例方法时。
You don't need to pass constructorInfo
as a parameter, as soon as you are calling a constructor, but not an instance method of an object.
var constructorInfo = typeof(Program).GetConstructor(
new[] { typeof(int), typeof(int), typeof(int) });
if (constructorInfo != null)
{
object[] lobject = new object[] { 1, 2, 3 };
constructorInfo.Invoke(lobject);
}
对于 KeyValuePair< T,U>
:
public Program(KeyValuePair<int, string> p)
{
Console.WriteLine(string.Format("{0}:\t{1}", p.Key, p.Value));
}
static void Main(string[] args)
{
var constructorInfo = typeof(Program).GetConstructor(
new[] { typeof(KeyValuePair<int, string>) });
if (constructorInfo != null)
{
constructorInfo.Invoke(
new object[] {
new KeyValuePair<int, string>(1, "value for key 1") });
}
Console.ReadLine();
}
这篇关于反射以ConstructorInfo调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文