简体   繁体   English

无法使用Activator.CreateInstance创建对象

[英]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 我正在尝试通过使用以下代码在我的项目中加载farpoint dll的旧版本

     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] 问题是创建实例后,farpoint的所有可用方法均不可用[例如-如果我直接创建对象,则实例可以使用saveExcel或savechanges之类的方法]

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

They are available, just not at compile time. 它们可用,只是在编译时不可用。 Activator.CreateInstance() returns an object . Activator.CreateInstance()返回一个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. Intellisense无法正常工作,因为正如@ C.Evenhuis所述, Activator.CreateInstance返回object ,因此您应该将其强制转换为适当的类型。

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方法。

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

By the way be carefull, while using Assembly.LoadFile . 顺便说一句,在使用Assembly.LoadFile要小心。 You may get more details from this article . 您可能会从本文中获得更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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