mardi 1 juin 2021

Modifying a dictionary contained in a dynamic object by string at runtime

I have constructed the following dynamic object:

public class DynamicModuleBase : DynamicObject, IModuleBase
{      
    // The inner dictionary.
    Dictionary<string, object> DynamicProperties = new Dictionary<string, object>();

    public DynamicModuleBase()
    {
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = DynamicProperties[binder.Name];

        return true;
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        DynamicProperties[binder.Name] = value;

        return true;
    }
}

Now I am trying to access my dictionary by string (ie. read existing or add values).
When I try to use typical reflection mechanism that works with non-dictionary types, it returns a null:

PropertyInfo info = ((dynamic)myObjectInstance).GetType().GetProperty(myPropertyNameAsString);    // Returns null

Why is this not working in the conventional way?
What is the right way to modify the dictionary by string?





Aucun commentaire:

Enregistrer un commentaire