最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to add keyvalue pair to `DynamicObject`? Why does it need a binder? - Stack Overflow

programmeradmin3浏览0评论

I have an instance of DynamicObject that I want to populate in a non-dynamic way with key/value pairs supplied at runtime.

void AddValue(DynamicObject obj, string name, object? value)
{
    // How to do it?
}

It seems like it should be possible to invoke TrySetMember(...) using the key/value pair, but I am stuck on how to implement or obtain an instance of SetMemberBinder. An implementation needs to define "fallback" behavior to "perform the binding of the dynamic set member operation if the target dynamic object cannot bind."

class RuntimePropertyBinder(string name) : SetMemberBinder(name, ignoreCase: false)
{
    public override DynamicMetaObject FallbackSetMember(
        DynamicMetaObject target,
        DynamicMetaObject value,
        DynamicMetaObject? errorSuggestion)
    {
        // What do we do here??
        throw new NotImplementedException();
    }
}

Maybe if I assume the target can bind, it is okay to throw? Even so, I'd like to understand the purpose of the binder and the fallback. I don't have control over the concrete implementation of DynamicObject, and I'd like to avoid making unnecessary assumptions about how it will invoke the binder.

发布评论

评论列表(0)

  1. 暂无评论