C# System.__ComObject 访问 Excel 文件时返回
我正在尝试通过下面的代码访问 Excel 文件:
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);
书籍变量的最后一行内容是 System.__ComObject
而在不同的应用程序代码中正在工作并且变量具有 ...Excel.WorkbookClass
代码>.
所以我想问一下这种奇怪行为的原因可能是什么。我已经尝试使用额外的 Missing.Value 参数调用 Workbooks.Open 但结果是相同的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
.NET COM 实现使用代理对象,这些代理是在内部生成的并派生自 System.__ComObject,因此这是正常行为。
它们是一种“动态对象”。
您可以将 __ComObject 强制转换为您需要的接口或类。
您可以毫无问题地将其转换为 WorkbookClass。
这完全取决于您如何获取实例...如果您使用 new 创建对象,例如
new WorkbookClass
,C# 将直接创建强类型对象。相反,如果对象是从 COM 函数或属性返回的,则它通常返回 __ComObject,这是因为 __ComObject 几乎可以是所有内容,并且可以转换为多个接口,当然 C# 不知道要返回什么,因此它返回这个特殊的一种“动态”对象。这些对象称为 RCW,代表运行时可调用包装器。
一个不错的阅读可以是http://www.codeproject.com/KB/cs/cominteropnet。 ASPX
.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