How to do dynamic object creation and method invocation in .NET 3.5

后端 未结 4 950
广开言路
广开言路 2021-01-06 23:52

How does the code looks that would create an object of class:

string myClass = \"MyClass\";

Of the above type, and then call



        
4条回答
  •  天涯浪人
    2021-01-07 00:33

    Assuming that your class is in your executing assembly, your constructor and your method is parameterless.

    Type clazz = System.Reflection.Assembly.GetExecutingAssembly().GetType("MyClass");
    
    System.Reflection.ConstructorInfo ci = clazz.GetConstructor(new Type[] { });
    object instance = ci.Invoke(null); /* Send parameters instead of null here */
    
    System.Reflection.MethodInfo mi = clazz.GetMethod("MyMethod");
    mi.Invoke(instance, null); /* Send parameters instead of null here */
    

提交回复
热议问题