在如下所示的非常简单的课程中,
class Program
{
public Program(int a, int b, int c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
我使用反射来调用构造函数
像这样的东西...
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);
}
但我收到一条错误消息“对象与目标类型构造函数信息不匹配”。
非常感谢任何帮助/评论。
提前致谢。
你不需要通过constructorInfo
作为参数,只要您调用构造函数,而不是对象的实例方法。
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);
}
For 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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)