无法使用Activator.CreateInstance创建对象

时间:2015-08-04 17:13:42

标签: c# asp.net asp.net-web-api farpoint-spread

我正在尝试使用下面的代码

在我的项目中加载旧版本的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);

问题是在创建实例后,所有可用的farpoint方法都不可用 [例如 - 如果我直接创建对象,则实例可以使用saveExcel或savechanges等方法]

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

2 个答案:

答案 0 :(得分:1)

它们可用,而不是在编译时。 Activator.CreateInstance()会返回object。你当然可以投射对象:

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

但这可能会超越使用反射来创建实例的全部目的。

您可以使用反射访问结果对象的所有成员,即:

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

答案 1 :(得分:1)

智能感知不起作用,因为正如所说的@ C.Evenhuis,Activator.CreateInstance会返回object,所以你应该把它投射到合适的类型。

如果在编译时未知类型,但您可以访问代码库,则可以尝试为其添加接口,并由您的类实现。然后将对象强制转换为该接口并使用它。 (我不知道你的目的,但是接口可以被视为所有类型的合同,你将动态加载。)

如果在编译时不知道type并且您无法访问代码库,则可以使用反射进行方法调用或使用dynamic代替。

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

顺便说一下,在使用Assembly.LoadFile时。您可以从此article获得更多详细信息。