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

前端 未结 2 728
忘了有多久
忘了有多久 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: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.

提交回复
热议问题