简体   繁体   English

C#迭代通用对象

[英]C# iterate generic object

Am moving from Excel VBA to VSTO using C#. 我正在使用C#从Excel VBA迁移到VSTO。 In VBA I had a 3 line custom function called IsInCollection as shown below: 在VBA中,我有一个名为IsInCollection的3行自定义函数,如下所示:

On Error Resume Next
Set obj = collectionObject(itemObject)
IsInCollection = Not (obj is Nothing)

I used it all the time to check if a given workbook was open, or if a workbook contained a sheet with a particular name, etc. Because the collection and the item arguments are defined as objects it would work with anything. 我一直用它来检查给定的工作簿是否已打开,或者工作簿是否包含具有特定名称的工作表,等等。由于将collection和item参数定义为对象,因此可以使用任何对象。

I'm trying to create the same utility function/method in managed code and am struggling mightily. 我正在尝试在托管代码中创建相同的实用程序功能/方法,并且努力工作。 The problem is with the collectionObject(itemObject) expression. 问题出在collectionObject(itemObject)表达式上。 C# doesn't allow me to just index an object as VBA did. C#不允许我像VBA那样仅索引对象。

If anybody can point me in the right direction it would be much appreciated. 如果有人能指出我正确的方向,将不胜感激。 From my searching I've been looking into QueryInterface but am not sure if that's where I should be looking. 从我的搜索中,我一直在研究QueryInterface,但是不确定是否应该在那儿。 It seems that an Excel object comes across as a System._ComObject , so presumably I need to iterate through that somehow(?). 似乎Excel对象是作为System._ComObject ,因此大概我需要以某种方式遍历该对象(?)。

TIA TIA

i think you want to check out LINQ. 我认为您想查看LINQ。 for example you can query collections like 例如,您可以查询类似的集合

IsInCollection = obj.Any(s => s != null);

The indexing operator in C# is [], not () as in VB. C#中的索引运算符是[],而不是VB中的()。 I'm not very familiar with COM though, so if the object you have is just an object/System._ComObject you might have to cast it to the appropriate type first, unless _ComObject has an indexer already. 我对COM不太熟悉,因此,如果您拥有的对象只是一个object / System._ComObject,则可能必须先将其转换为适当的类型,除非_ComObject已经具有索引器。

It seems that finding out what type a _ComObject really is can be be a bit difficult, so you might wanna try a trick I found at http://www.mztools.com/articles/2006/mz2006013.aspx : 似乎很难发现_ComObject的真正类型,因此您可能想尝试一下我在http://www.mztools.com/articles/2006/mz2006013.aspx上找到的技巧:

var typeName = Microsoft.VisualBasic.Information.TypeName( collectionObject );

I also suspect you could use the System.ComponentModel.TypeDescriptor class. 我也怀疑您可以使用System.ComponentModel.TypeDescriptor类。

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

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