C# System.__ComObject returned when accessing Excel file

元气小坏坏 提交于 2019-12-10 17:57:26

问题


I am trying to access Excel file by code below:

Microsoft.Office.Interop.Excel.Application ObjExcel
  = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook book;
Microsoft.Office.Interop.Excel.Worksheet sheet;
Excel.Range range1 = null, range2 = null;
CultureInfo ci = new CultureInfo("en-US");
Thread thisThread = Thread.CurrentThread;
thisThread.CurrentCulture = new CultureInfo("en-US");
book = ObjExcel.Workbooks.Open(LinguisticInstructionsFileName);

At last line content of book variable is System.__ComObject while in different app code is working and variable has ...Excel.WorkbookClass.

So I would like to ask what might be the reason for this strange behavior. I already tried to call Workbooks.Open with extra Missing.Value args but result was the same.


回答1:


.NET COM implementation uses proxy objects, these proxies are generated internally and derive from System.__ComObject so that's a normal behaviour. They are a sort of "dynamic objects". You can cast the __ComObject to the interface or the class you need. You can cast it to WorkbookClass without problems.

It all depends on how you get the instance... if you create an object with new, for example, new WorkbookClass, C# will directly create the strong typed object. Instead if the object is returned from a COM function or a property it returns often a __ComObject, this because the __ComObject can be almost everything and can be casted to several interfaces, of course C# don't know what to return so it returns this special kind of "dynamic" object. These objects are called RCW that stands for Runtime Callable Wrapper.

A nice read can be http://www.codeproject.com/KB/cs/cominteropnet.aspx



来源:https://stackoverflow.com/questions/8211752/c-sharp-system-comobject-returned-when-accessing-excel-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!