简体   繁体   中英

How to control dynamic" to not throw exceptions

I have a piece of code that tried to get the BarID from an object like this:

try
{

     dynamic dynItem = (dynamic)foo;
     string barId = dynItem.BarID;
}
catch (RuntimeBinderException)
{
       // Deliberately swallow any errors due to late-binding
}

Note that foo is a COM object and there are many COM interfaces that expose it, and I cannot simply try to cast to each of them.

The problem is that the dynamic implementation is throwing that RuntimeBinderException causing Visual Studio to break because of "first chance exception" and I need to avoid this.

Any idea if I can access some API (Microsoft.Dynamic?) to see to call BarId without throwing exceptions, much like dynamic is probably doing under the covers?

Note:

  • reflection won't work because of COM

  • I can use the COM IDispatch interface but this too low level (I'll have to spend the next 2 days writing unit tests...)

I don't believe you can test this without an exception being thrown. I don't think there's any magic that's happening under the covers you can't see. One thing you could try is have all your objects implenent an IHaveBarID Interface.

Then you can write:

IHaveBarID dynItem = foo as IHaveBarID;
if (dynItem != null)
    string  barID = dynItem.BarID;

Otherwise, you'll either need to use IDispatch or tell VS to not break on that specific type of exception.

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