c# - create exact instance from class name -


i have 2 classes: class1 , class2

class class1 {     public void method(); }  class class2 {     public void method(); } 

in place have class type , want create instance it. type typeof(class1) or typeof(class2)

public void createinstance(type type) {     var instance = activator.getinstance(type);     instance.method(); //compile error: object doesn't contain method } 

a solution define interface classes implement interface.

interface iinterface {     void method(); }  public void createinstance(type type) {     var instance = activator.getinstance(type);     ((iinterface)instance).method(); } 

because can't access class definition can't this. how can this?

this need:

public void createinstance(type type) {     var instance = activator.createinstance(type);     type.getmethod("method").invoke(instance, null); } 

or, alternatively, use dynamic:

public void createinstance(type type) {     dynamic instance = activator.createinstance(type);     instance.method(); } 

nb: had getinstance instead of createinstance in code, corrected it.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -