Using a dynamic dictionary in C #

I am using dynamic dictionary in C #. The problem I am facing is the TryGetMember behavior, which I override in the dynamic dictionary class.

Here is the dynamic dictionary code.

class DynamicDictionary<TValue> : DynamicObject
{
    private IDictionary<string, TValue> m_dictionary;

    public DynamicDictionary(IDictionary<string, TValue> a_dictionary)
    {
        m_dictionary = a_dictionary;
    }

    public override bool TryGetMember(GetMemberBinder a_binder, out object a_result)
    {
        bool returnValue = false;

        var key = a_binder.Name;
        if (m_dictionary.ContainsKey(key))
        {
            a_result = m_dictionary[key];
            returnValue = true;
        }
        else            
            a_result = null;

        return returnValue;
    }
}

Here TryGetMember will be called at runtime whenever we refer to some key from the outside, but it is strange that the binder name element, which always gives the key that we refer from outside, always resolves the key name written as alphabetic characters.

eg. if the DynamicDictionary object is executed as:

Dictionary<string,List<String>> dictionaryOfStringVsListOfStrings; 

//here listOfStrings some strings list already populated with strings
dictionaryOfStringVsListOfStrings.Add("Test", listOfStrings); 
dynamic dynamicDictionary_01 = new 
    DynamicDictionary<List<String>(dictionaryOfStringVsListOfStrings);

string somekey = "Test";

//will be resolve at runtime
List<String> listOfStringsAsValue = dynamicDictionary_01.somekey 

, , "somekey" a_binder (i.e a_binder.Name = "somekey" ). a_binder.Name = "Test", listOfStrings (.. "Test", , ).

?

+3
1

, .

, , - ​​ - ​​ , (, "somekey" )).

, - Dictionary<string,List<String>> :

List<String> listOfStringsAsValue = dictionary[somekey];

EDIT: , :

public class Foo // TODO: Come up with an appropriate name :)
{
    private readonly Dictionary<string, List<string>> dictionary =
        new Dictionary<string, List<string>>();

    public List<string> this[string key]
    {
        get
        {
            List<string> list;
            if (!dictionary.TryGetValue(key, out list))
            {
                list = new List<string>();
                dictionary[key] = list;
            }
            return list;
        }
    }
}

:

foo["first"].Add("value 1");
foo["second"].Add("value 2")
foo["first"].Add("value 1.1");

, , .

, DynamicObject.

+5

Source: https://habr.com/ru/post/1755984/


All Articles