sca*_*man 90 c# reflection constructor
我有以下场景:
class Addition{
public Addition(int a){ a=5; }
public static int add(int a,int b) {return a+b; }
}
Run Code Online (Sandbox Code Playgroud)
我通过以下方式调用另一个类:
string s="add";
typeof(Addition).GetMethod(s).Invoke(null, new object[] {10,12}) //this returns 22
Run Code Online (Sandbox Code Playgroud)
我需要一种类似于上面的反射语句的方法来创建一个Addition类型的新对象 Addition(int a)
所以我有字符串s= "Addition",我想用反射创建一个新对象.
这可能吗?
Jon*_*eet 158
我不认为GetMethod会这样做,不 - 但GetConstructor愿意.
using System;
using System.Reflection;
class Addition
{
public Addition(int a)
{
Console.WriteLine("Constructor called, a={0}", a);
}
}
class Test
{
static void Main()
{
Type type = typeof(Addition);
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(int) });
object instance = ctor.Invoke(new object[] { 10 });
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:是的,Activator.CreateInstance也会工作.使用GetConstructor,如果你想拥有的东西上更多的控制,找出参数名称等Activator.CreateInstance是伟大的,如果你只是想虽然调用构造函数.
| 归档时间: |
|
| 查看次数: |
87961 次 |
| 最近记录: |