我有这堂课:
public class StructTest
{
public StructTest()
{
}
public void Start()
{
// do something
}
}
我想动态创建StructTest类的实例,并使用反射执行其方法“Start”。但是下面的代码抛出异常:
Assembly current = Assembly.GetExecutingAssembly();
string nomeClasse = "StructTest";
foreach (var classInAssembly in current.GetTypes().Where(p => p.IsClass).Where(p => p.Name.Equals(nomeClasse)))
{
Type type = classInAssembly.GetType();
var classe = Activator.CreateInstance(type, null); // Here the VS says theres no paramterless contructor for this class without parameters
IEnumerable<MethodInfo> methodList = classInAssembly.GetMethods().Where(p => p.Name.Equals("Start"));
MethodInfo method = methodList.First();
method.Invoke(classe, null);
}
答案 0 :(得分:2)
foreach (var type in current.GetTypes().Where(p => p.IsValueType && p.Name.Equals(nomeClasse))) {
var classe = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("Start");
method.Invoke(classe, null);
}