Как я получаю доступ к Объекту Словаря с помощью Выражений Linq

Я хочу создать Лямбда-выражение с помощью Выражений Linq, который может получить доступ к объекту в словаре стилей 'набора свойств' с помощью Индекса строк. Я использую.Net 4.

    static void TestDictionaryAccess()
    {
        ParameterExpression valueBag = Expression.Parameter(typeof(Dictionary<string, object>), "valueBag");
        ParameterExpression key = Expression.Parameter(typeof(string), "key");
        ParameterExpression result = Expression.Parameter(typeof(object), "result");
        BlockExpression block = Expression.Block(
            new[] { result },               //make the result a variable in scope for the block
            Expression.Assign(result, key), //How do I assign the Dictionary item to the result ??????
            result                          //last value Expression becomes the return of the block
        );

        // Lambda Expression taking a Dictionary and a String as parameters and returning an object
        Func<Dictionary<string, object>, string, object> myCompiledRule = (Func<Dictionary<string, object>, string, object>)Expression.Lambda(block, valueBag, key).Compile();

        //-------------- invoke the Lambda Expression ----------------
        Dictionary<string, object> testBag = new Dictionary<string, object>();
        testBag.Add("one", 42);  //Add one item to the Dictionary
        Console.WriteLine(myCompiledRule.DynamicInvoke(testBag, "one")); // I want this to print 42
    }

В вышеупомянутом методе тестирования я хочу присвоить значение объекта Словаря т.е. testBag ["один"] в результат. Обратите внимание, что я присвоил переданный в Строке ключа в результат для демонстрации Присваивать вызова.

9
задан Michael Dausmann 21 June 2010 в 15:22
поделиться

1 ответ

Вы можете использовать следующее для доступа к свойству Item словаря Dictionary

Expression.Property(valueBag, "Item", key)

Вот изменение кода, которое должно помочь.

ParameterExpression valueBag = Expression.Parameter(typeof(Dictionary<string, object>), "valueBag");
ParameterExpression key = Expression.Parameter(typeof(string), "key");
ParameterExpression result = Expression.Parameter(typeof(object), "result");
BlockExpression block = Expression.Block(
  new[] { result },               //make the result a variable in scope for the block           
  Expression.Assign(result, Expression.Property(valueBag, "Item", key)),
  result                          //last value Expression becomes the return of the block 
);
13
ответ дан 4 December 2019 в 15:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: