简体   繁体   中英

Creating Object from Class name specified in string

I have a dropdownlist on a webpage which has list of all classnames , in C# code I need to instantiate object of selected items from dropdownlist and call method of it . All classes have similar methods .

 String sCalclationType = "N0059";
 var Calculator = Activator.CreateInstance("Calculator", sCalclationType ); 
 var count =  Calculator.DoCalculation();

I tried casting which shows "Cannot convert type 'System.Runtime.Remoting.ObjectHandle' to 'CypressDataImport.DiabetesHelper.NQF0059" , Also I need to cast to type which needs to be same as dropdown item so not sure how to do that .

//var calc = (N0059)Calculator; 

How do I handle this scenario ?

See here:

Try this:

String sCalclationType = "N0059";
ObjectHandle handle = Activator.CreateInstance("Calculator", sCalclationType ); 
var Calculator = (N0059)handle.Unwrap();
var count = Calculator.DoCalculation();

or

String sCalclationType = "N0059";
ObjectHandle handle = Activator.CreateInstance("Calculator", sCalclationType );
Object p = handle.Unwrap();
Type t = p.GetType();
MethodInfo method = t.GetMethod("DoCalculation");
var count = method.Invoke(p, null); 

You need to return the wrapped object returned by the Activator.CreateInstace() method.

To do that have a look at ObjectHandle.Unwrap on MSDN .

Please also make sure you are using the fully qualified name of your type as explained here .

Below is an example of usage:

Object obj = Activator.CreateInstance(System.Reflection.Assembly.GetExecutingAssembly().FullName, "CypressDataImport.DiabetesHelper.NQF0059.N0059").Unwrap();
N0059 calculator= (N0059)obj;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM