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
Post a Comment