如何创建对象并使用反射执行方法?

时间:2013-09-02 00:39:29

标签: c# .net reflection

我有这堂课:

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);
        }

1 个答案:

答案 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);
}