简体   繁体   中英

C# iterate generic object

Am moving from Excel VBA to VSTO using C#. In VBA I had a 3 line custom function called IsInCollection as shown below:

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.

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. C# doesn't allow me to just index an object as VBA did.

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. It seems that an Excel object comes across as a System._ComObject , so presumably I need to iterate through that somehow(?).

TIA

i think you want to check out LINQ. for example you can query collections like

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

The indexing operator in C# is [], not () as in 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.

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 :

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

I also suspect you could use the System.ComponentModel.TypeDescriptor class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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