简体   繁体   中英

not able to create object with Activator.CreateInstance

I am trying to load the old version of farpoint dll in my project by using below code

     System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(@"FarPoint.Web.Spread.dll");
    System.Type MyDLLFormType = assembly.GetType("FarPoint.Web.Spread.FpSpread");
    var c = Activator.CreateInstance(MyDLLFormType);

The problem is after the instance is created, all the available methods of farpoint are not available [ for example - if i create the object directly the methods like saveExcel or savechanges are available with the instance]

                FpSpread fpProxyObject = new FpSpread();
                fpProxyObject.SaveExcel();

They are available, just not at compile time. Activator.CreateInstance() returns an object . You could of course cast the object:

var c = Activator.CreateInstance(...)
FpSpread fpProxyObject = (FpSpread)c;

But that would probably beat the whole purpose of using reflection to create the instance.

You can access all members of the result object by using reflection, ie:

MethodInfo saveExcelMethod = c.GetType().GetMethod("SaveExcel");
if (saveExcelMethod == null) throw new ApplicationException("Incorrect version of FarPoint");
saveExcelMethod.Invoke(c);

Intellisense is not working, because, as said @C.Evenhuis, Activator.CreateInstance returns object , so you should cast it to appropriate type.

If type is not known at compile time, but you have access to a code-base, you could try to add interface for it, and implement it by your class. Then cast object to that interface and use it. (I don't know your purpose, but interface could be treated as a contract for all the types, that you will load dynamically).

If type is not known at compile time and you have no access to a code-base, you could use reflection for method invocation or use dynamic instead.

dynamic c = Activator.CreateInstance(MyDLLFormType);
c.SaveExcel(); // this method invocation will be bound in runtime.

By the way be carefull, while using Assembly.LoadFile . You may get more details from this article .

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