now*_*ed. 7 .net c# reflection .net-4.0 visual-studio-2010
在如下的非常简单的类中,
class Program
{
public Program(int a, int b, int c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用反射来调用构造函数
像这样的东西......
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);
}
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误,说"对象与目标类型构造函数不匹配".
任何帮助/评论非常感谢.提前致谢.
hor*_*rgh 14
你并不需要通过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);
}
Run Code Online (Sandbox Code Playgroud)
用于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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11779 次 |
| 最近记录: |