Lots of first chance Microsoft.CSharp.RuntimeBinderExceptions thrown when dealing with dynamics

前端 未结 2 717
忘了有多久
忘了有多久 2020-11-30 05:38

I\'ve got a standard \'dynamic dictionary\' type class in C# -

class Bucket : DynamicObject
{
    readonly Dictionary m_dict = new Dic         


        
相关标签:
2条回答
  • 2020-11-30 05:56

    This was bothering me, too. I added the exception to the exceptions list so that I could deselect it. Just follow these steps:

    • From the Debug menu, select Exceptions.
    • Click the "Add..." button on the bottom right.
    • Choose "Common Language Runtime Exceptions" from the Type dropdown.
    • Type "Microsoft.CSharp.RuntimeBinder.RuntimeBinderException" as the name.
    • Click OK.
    • The exception type will now appear on the list. Just deselect it.

    I wish this setting could be saved across solutions, but I don't think it can, so you'll have to reapply this setting on every solution.

    0 讨论(0)
  • 2020-11-30 05:59

    Whenever a property on a dynamic object is resolved, the runtime tries to find a property that is defined at compile time. From DynamicObject doco:

    You can also add your own members to classes derived from the DynamicObject class. If your class defines properties and also overrides the TrySetMember method, the dynamic language runtime (DLR) first uses the language binder to look for a static definition of a property in the class. If there is no such property, the DLR calls the TrySetMember method.

    RuntimeBinderException is thrown whenever the runtime cannot find a statically defined property(i.e. what would be a compiler error in 100% statically typed world). From MSDN article

    ...RuntimeBinderException represents a failure to bind in the sense of a usual compiler error...

    It is interesting that if you use ExpandoObject, you only get one exception when trying to use the property:

    dynamic bucket = new ExpandoObject();
    bucket.SomeValue = 45;
    int value = bucket.SomeValue; //<-- Exception here
    

    Perhaps ExpandoObject could be an alternative? If it's not suitable you'll need to look into implementing IDynamicMetaObjectProvider, which is how ExpandoObject does dynamic dispatch. However, it is not very well documented and MSDN refers you to the DLR CodePlex for more info.

    0 讨论(0)
提交回复
热议问题